After learning the knowledge of polymorphism, because polymorphism is such a tool of "cleverness", it seems that everything should be inherited. But if the use of inheritance technology, it will make their own design unnecessarily complicated. In fact, when we build a new class on the basis of a ready-made class, it becomes extraordinarily complicated to choose inheritance first.
A better idea is to choose "compositing" first-if you're not quite sure which one you should use. Synthesis does not force our programming into an inherited hierarchical structure. At the same time, compositing is more flexible because a type (and behavior) can be dynamically selected, and inheritance requires that a type be known accurately during compilation. This is illustrated in the following example:
: Transmogrify.java
//dynamically changing the behavior of
//an object via composition.
Interface Actor {
void Act ();
}
Class Happyactor implements Actor {public
Void Act () {
System.out.println ("Happyactor");
}
Class Sadactor implements Actor {public
Void Act () {
System.out.println ("Sadactor");
}
Class Stage {
Actor a = new Happyactor ();
void Change () {a = new Sadactor ();}
void Go () {a.act ();}
}
public class Transmogrify {public
static void Main (string[] args) {
Stage s = new Stage ();
S.go (); Prints "Happyactor"
s.change ();
S.go (); Prints "Sadactor"
}
}///:~
Here, a stage object contains a handle that points to a actor, which is initialized to a Happyactor object. This means that go () produces a specific behavior. However, because the handle can be sadactor or combined with a different object during run time, the handle of the object can be replaced in a, and then the behavior resulting from go () will change. As a result, we get a lot of flexibility during the run. In contrast, we cannot use different forms for inheritance during runtime, and it requires complete determination during compilation.
A general design criterion is to use the difference between the behavior of the inheritance expression, and to express the change of state with the member variable. In the above example, both were applied: two different classes were inherited to express the difference between the Act () method, while stage allowed its own state to change through the synthesis technology. In this case, that state of change also produces a change in behavior.