Java Reference
In-Depth Information
as well (comparing alphabetically based on name, for instance), or maybe this only
applies to some subclasses of a person, for example, VIPPerson . With subclassing,
you describe a hierarchy of inherited behavior. With interfaces, you describe a set
of behavior that can be implemented by classes.
So why would it make sense to apply both? First of all, using this approach
allows a certain freedom. For instance, when you use and pass around the
interface in your client code, you can later define a second abstract class (with
descendants) that also implements this interface. These two sets of hierarchies
can then differ from each other, but since they both implement the same inter-
face, your client code will continue to work as normal, for both abstract classes
and all their descendants, without you having to perform heavy refactoring.
However, this doesn't mean that you should go out of your way to always define
an interface and an abstract class. If you find yourself adding all the methods in
the abstract class as signatures to the interface, the added benefit of the inter-
face itself is little, especially since there is no immediate desire to create a sec-
ond abstract class implementing that interface. Even if such a desire did arise, it
is likely that you could refactor your current class tree to add the new abstract
class as a subclass of the existing abstract class, since they appear to share so
much behavior anyway.
The best thing to do is pick either an abstract class (a class is a ... ) or an interface
(a class can do ... ) and refactor only when a need arises.
One particular real‐life scenario you have seen before uses the decorator pattern,
where the abstract class and its descendants contain most of the shared code and
implement an interface (in simple cases, the abstract hierarchy can be replaced with
a single class). The decorator classes can then form a second hierarchy of abstract
classes and descendants (or can also be implemented as a collection of unrelated
classes in simple cases), and also implement the interface. The interface then
provides signatures for the functionality the decorators can tweak. Figures 12-1
through 12-4 provide a schematic overview of these cases.
interface Window
class NormalWindow
implements Window
class WindowDecorator
implements Window
Window instanceToDecorate;
Simplest case: shared interface, two concrete classes
figure 12-1  
continues
 
Search WWH ::




Custom Search