Decorator pattern

The decorator pattern allows us to "wrap" an object that provides core functionality with other objects that alter that functionality. Any object that uses the decorated object will interact with it in exactly the same way as if it were undecorated (that is, the interface of the decorated object is identical to the core object).

There are two primary uses of the decorator pattern:

• Enhancing the response of a component that is sending data to a second component

• Supporting multiple optional behaviors

The second option is often a suitable alternative to multiple inheritance. We can construct a core object, and then create a decorator around that core. Since the decorator object has the same interface as the core object, we can even wrap the new object in other decorators. Here's how it looks in UML:

Decorator Pattern Example

Here, Core, and all the decorators implement a specific Interface. The decorators maintain a reference to another instance of that Interface, via composition. When called, the decorator will do some added processing before or after calling its wrapped interface. The wrapped object may be another decorator, or the core functionality; multiple decorators may wrap each other, but the object in the "center" of all those decorators will provide core functionality.

Was this article helpful?

0 0

Post a comment