288 | Chapter 8: Observer Pattern
works fine. What’s more, using thespaceWarriorinstance, we could redefine it as an
Alien( ) instance, and it’d still work fine. Change the last part to:
//Program to interface
var spaceWarrior:SpaceWarrior=new Earthling( );
spaceWarrior.useWeapon( );
spaceWarrior=new Alien( );
spaceWarrior.useWeapon( );
Now, the output shows:
Zaaaapp!!!
Ka Boom!!!
Zaaaapp!!!
As you can see, by programming to the interface, the instances are far more flexible.
We don’t have to know what’s in the function (interface) or what it’ll do, we just
know that it will do what it’s supposed to, depending on the constructor we use.
Object Composition
To see why object composition is favored over class inheritance, we need to see what
each does. Previous chapters have used both object composition and inheritance,
and so you may have some idea of what each does. Both concepts were introduced in
Chapter 1, but because the Observer design pattern clearly illustrates the use of com-
position, we are reviewing it here again.
Keeping in mind that the comparison between inheritance and object composition
relates to building flexible and reusable software elements, we have a base for com-
parison. So we can restate the principle as:
For improved flexible and reusable software, favor object composition over class
inheritance.
Reusable software developed through inheritance is relatively straightforward. Devel-
opers take an existing class and use it again with the particulars created through sub-
classes. Because the internals of the objects are often visible to the subclasses, the
termwhite-box reuseis applied to this implementation.
Object composition, by contrast, achieves new functionality by bringing together
existing objects. The composition process can be understood as one class using
another class’s functionality, whereas inheritance depends on the class having the
functionality. So, in composition, one classuses afunctionality of another class,
while in inheritance, a sub classis-aclass with functionality inherited from another
class. Because object composition hides the internal details, the termblack-box reuse
is applied to this kind of development.
Inheritance has some advantages in being simple to create, visible, and relatively sim-
ple for making certain types of changes. For example, if you want a change to be