The Decorator

Intent: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality (Gamma et al., 1994).

Example: Processing an image for display or to send to a printer can involve many different manipulations depending on the effect desired and the capabilities (color gamut, etc.) of the target device.

These manipulations can include spatial passes, Fourier transformations, affine transformations, and so forth. Each does something different to alter the way the image appears. Once filtered, the image is displayed or printed.

An image processing system should allow for none, one, some, or all of these manipulations to be applied, and in any order desired by the end user.

images

Figure 7: Decorator example diagram.

Qualities and Principles: Each decorator does a single kind of decoration, making them strongly cohesive. The clients couple only to the interface of the abstraction (ImageOut in the example). Which decorators are in use, the order in which they operate, and the final destination are all encapsulated from clients, and thus all are open-closed. The interface comes from no particular implementation, but from the clients’ needs.

Testing: Each decorator can be tested using a mock of the decorated object to ensure it adds the proper decoration to the data it has passed, and that it passes on to the next object.

Questions and Concerns: Ideally, all decorators and the decorated objects should have the same interface to allow for maximum flexibility. An adapter (see p. 18) can be used when this is not true. A decorator is typically implemented using a template method (see p. 54) to separate the decorating behavior from the common handoff to the next behavior (the OutputImage() method in the example is a template method).

Decorator chains nearly always have business rules regarding which combinations are permissible and which are not, including constraints on sequence, and which decorators can and cannot be used together. Because of this, some kind of creational (factory) pattern is typically used to capture and enforce these restrictions and to separate them from client concerns.

For more information: https://tinyurl.com/yy3ur56t

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

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