Field Notes: Using the Decorator Pattern

The power of the Decorator pattern requires that the instantiation of the chains of objects be completely decoupled from the Client objects that use it. This is most typically accomplished through the use of factory objects that instantiate the chains based upon some configuration information.

The Decorator Pattern: Key Features

Intent Attach additional responsibilities to an object dynamically.
Problem The object that you want to use does the basic functions you require. However, you may need to add some additional functionality to the object, occurring before or after the object's base functionality. Note that the Java foundation classes use the Decorator pattern extensively for I/O handling.
Solution Allows for extending the functionality of an object without resorting to subclassing.
Participants and Collaborators The ConcreteComponent is the class having function added to it by the Decorators. Sometimes classes derived from ConcreteComponent are used to provide the core functionality, in which case ConcreteComponent is no longer concrete, but rather abstract. The Component defines the interface for all of these classes to use.
Consequences Functionality that is to be added resides in small objects. The advantage is the ability to dynamically add this function before or after the functionality in the ConcreteComponent. Note: While a decorator may add its functionality before or after that which it decorates, the chain of instantiation always ends with the ConcreteComponent.
Implementation Create an abstract class that represents both the original class and the new functions to be added to the class. In the decorators, place the new function calls before or after the trailing calls to get the correct order.
GoF Reference Pages 175–184.

Figure 15-7. Standard, simplified view of the Decorator pattern.



I have used the Decorator to wrap precondition and postcondition tests on an object to be tested with nice results. During test, the first object in the chain can do an extensive test of preconditions prior to calling its trailing object. Immediately after the trailing object call, the same object calls an extensive test of postconditions. If I have different tests I want to run at different times, I can keep each test in a different Decorator and then chain them together according to the battery of tests I want to run.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.72.232