kumikill
5/11/2018 - 12:39 AM

Decorator

Source: http://www.vincehuston.org/dp/decorator.html

Intent

  • Attach additional responsibilities to an object dynamically. Decoratoes provde a flexible alternative to subclassing for extending functionality.
  • Client-specified embellishment of a core object by recursively wrapping it.
  • Wrapping a gift, putting it in a box, and wrapping the box.

Problem

You want to add behavior or state to individual objects at runtime. Inheritance is not feasible because it is static and applies to an entire class.

Example

The Decorator attaches additional responsibilities to an object dynamically. The ornaments that are added to pine or fir trees are examples of Decorators. Lights, garland, candy canes, glass ornaments, etc. can be added to a tree to give it a festive look. The ornaments do not change tree itself which is recognizable as a Christmas tree regardless of particular ornaments used. As an example of additional functionality, the addition of lights allows one to "light up" a Christmas tree.

Although paintings can be hung on a wall with or without frames, frames are often addes, and it is the frame which is actually hung on the wall. Prior to hanging, the paintings may be matted and framed, with the painting, matting, and frame formating a single visual component.