Pedro J Toro
cs509: Software Design

Pattern: Decorator

Synopsis

The Decorator pattern dynamically attaches additional responsibilities or functions to an object. It is also a sort of Wrapper.

Context

Generally used to avoid subclassing a class that has become heavy. Window objects in X are a fairly large class, with a variety of decorators available to change their appearence. This does not require the underlying class to change. <taken from Professor Pollice >

Forces

To dynamically add additional functionality to a particular object, but not the whole class. And do so without making subclasses.

Solution

 Interface matches that of original object
• Contains object being decorated
• Can add new states, behavior, or both
• Can be recursive

The general pattern for the Decorator pattern is as follows:

Consequences

Implementation

Given an interface named Action with two methods, act1() and act2(),
and a concrete version of this interface named ConcreteAction,

the Decorator would be a class that implements Action and whose constructor takes an Action (usually ConcreteAction).

The code would look like this:

public class ActionDecorator implements Action
{
    private Action action;

    public ActionDecorator(Action action)
   {
       this.action = action;
   }

   public void act1()
   {
      action.act1();
   }

   public void act2()
   {
   // do nothing
   }
}

example taken from http://www3.sympatico.ca/prime_matrix/seg3110/decorator/ page 13.

Related Patterns

Adapter - provides a different interface
Proxy - provides the same interface
Composite - can be composed