Reusing the implementation(复用具体实现)

来源:互联网 发布:dnf鬼泣紫阵减防数据 编辑:程序博客网 时间:2024/04/28 19:28

Once a class has been created and tested, it should (ideally) represent a useful unit of code. 一旦类被创建并被测试完,那么它就应该(在理想情况下)代表一个有用的代码单元。

It turns out that this reusability is not nearly so easy to achieve as many would hope;事实证明,这种复用性并不容易达到我们所希望的那种程度;

it takes experience and insight to produce a reusable object design.产生一个可复用的对象设计需要丰富的经验和敏锐的洞察力。

But once you have such a design, it begs to be reused. 但是一旦你有了这样的设计,它就可供复用。

Code reuse is one of the greatest advantages that object-oriented programming languages provide. 代码复用是面向对象程序设计语言所提供的最了不起的优点之一。


The simplest way to reuse a class is to just use an object of that class directly, but you can also place an object of that class inside a new class.最简单地复用某个类的方式就是直接使用该类的一个对象,此外也可以将那个类的一个对象置于某个新的类中。

We call this "creating a member object."我们称其为“创建一个成员对象”。

Your new class can be made up of any number and type of other objects, in any combination that you need to achieve the functionality desired in your new class.新的类可以由任意数量、任意类型的其他对象以任意可以实现的类中想要的功能的方式所组成。

Because you are composing a new class from existing classes, this concept is called composition (if the composition happens dynamically, it's usually called aggregation).因为是在使用现有的类合成新的类,所以这种概念被称为组合(composition),如果组合是动态发生的,那么它通常被称为聚合(aggregation).

Composition is often referred to as a "has-a" relationship, as in "A car has an engine."组合常被视为"has-a"拥有关系,就像我们常说的"汽车拥有引擎".


Composition  comes with a great deal of flexibility.组合带来了极大的灵活性.

The member objects of your new class are typically private, making them inaccessible to the client programmers who are using the class.新类的成员对象通常都被生命为private,使得使用新类的客户端程序员不能访问它们.

This allows you to change those members without disturbing existing client code.这也使得你可以在不干扰现有客户端代码的情况下,修改这些成员.

You can also change the member objects at run time, to dynamically change the behavior of your program.也可以在运行时修改这些成员对象,以实现动态修改程序的行为.

Inheritance, which is described next, does not have this flexibility since the compiler must place compile-time restrictions on classes created with inheritance.下面要讨论的集成并不具备这样的灵活性,因为编译器必须对通过继承而创建的类施加编译时的限制.


Because inheritance is so important in object-oriented programming, it is often highly emphasized, and the new programmer can get the idea that inheritance should be used everywhere.由于继承在面向对象程序设计中如此重要,所以它经常被高度强调,于是程序员新手就会有这样的印象:处处都应该使用继承.

This can result in awkward and overly complicated designs.这会导致难以使用并过分复杂的设计.

Instead, you should first look to composition when creating new classes, since it is simpler and more flexible.实际上,在建立新类时,应该首先考虑组合,因为它更加简单灵活.

If you take this approach, your designs will be cleaner.如果采用这种方式,设计会变得更加清晰.

Once you've had some experience, it will be reasonably obvious when you need inheritance.一旦有了一些经验之后,便能够看出必须使用继承的场合了.

0 1
原创粉丝点击