Design Patterns: Elements of Reusable Object-Oriented Software
247
Composite versus Decorator versus Proxy
Composite (183) and Decorator (196) have similar structure diagrams, reflecting
the fact that both rely onrecursive composition to organize an open-ended number
of objects.This commonality might tempt you to think of a decorator object as
adegenerate composite, but that misses the point of the Decoratorpattern. The
similarity ends at recursive composition, again becauseof differing intents.
Decorator is designed to let you add responsibilities to objectswithout
subclassing. It avoids the explosion of subclasses that canarise from trying to
cover every combination of responsibilitiesstatically. Composite has a different
intent. It focuses onstructuring classes so that many related objects can be
treateduniformly, and multiple objects can be treated as one. Its focus isnot
on embellishment but on representation.
These intents are distinct but complementary. Consequently, theComposite and
Decorator patterns are often used in concert. Both leadto the kind of design in
which you can build applications just byplugging objects together without defining
any new classes. There willbe an abstract class with some subclasses that are
composites, somethat are decorators, and some that implement the fundamental
buildingblocks of the system. In this case, both composites and decoratorswill
have a common interface. From the point of view of the Decoratorpattern, a composite
is a ConcreteComponent. From the point of view ofthe Composite pattern, a decorator
is a Leaf. Of course, they don't
have
to be used together and, as we have seen,
their intentsare quite different.
Another pattern with a structure similar to Decorator's is Proxy (233).Both
patterns describe how to provide a level of indirection to anobject, and the
implementations of both the proxy and decoratorobject keep a reference to another
object to which they forward requests. Once again, however, they are intended
for different purposes.
Like Decorator, the Proxy pattern composes an object and provides anidentical
interface to clients. Unlike Decorator, the Proxy pattern isnot concerned with
attaching or detaching properties dynamically, andit's not designed for recursive
composition. Its intent is to providea stand-in for a subject when it's
inconvenient or undesirable toaccess the subject directly because, for example,
it lives on a remotemachine, has restricted access, or is persistent.
In the Proxy pattern, the subject defines the key functionality, andthe proxy
provides (or refuses) access to it. In Decorator, thecomponent provides only part
of the functionality, and one or moredecorators furnish the rest. Decorator
addresses the situation wherean object's total functionality can't be determined
at compile time,at least not conveniently. That open-endedness makes recursive
Do'stlaringiz bilan baham: |