Decorator Pattern

Published by

on

decorator Pattern

The Decorator Pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.

What does that mean ?

  • A Decorator Pattern can help attach additional responsibilities to an Object dynamically ( runtime instead of compile time ).
  • An alternative approach to having multiple sub classes.
  • Better way to create an object out of composition at runtime.

Let us consider a Coffee shop that sells variety of servings like Espresso , Decaf etc.

If we go about creating a class for each of the variety of coffee served there would be a Class explosion soon and things will go out of hand…

BadDesign_ClassExplosion

Decorator pattern to the rescue. A typical decorator pattern is made up of both “has a” and “is a” relationship with the base Class. Shown in the UML below

GoodDesignDecorator

Now based on the type of Coffee one order the cost of Coffee will change. One could have the following combination for example:

Assume cost of Caramel and WhippedCream addOn is a $1 each and Base version of Espresso is $3 and say Decaf is $2.

  1. Espresso with Caramel  and WhippedCream ( Cost = 3 + 1 + 1 )
  2. Espresso with WhippedCream ( Cost = 3 + 1 )
  3. Decaf with Caramel ( Cost = 2 + 1 )

One can see that with the introduction of Decorator pattern the possibilities of Coffee variety is not limited 🙂 .

A general UML diagram for Decorator Pattern will look like this

Decorator_PatternUML.png

Now for some sample Code , JAVA !

abstract class Beverage {
    public abstract float cost();
}

abstract class AddOnDecorator : Beverage {
    public abstract float cost();
}

class Espresso : Beverage {
    public float cost(){
       return 3; // assuming cost of Espresso to be $3
    }
}

class CaramelDecorator : AddOnDecorator {
    public CaramelDecorator(Beverage b)
    {
        this.beverage = b;
    }
    public float cost()
    {
        return this.beverage.cost() + 1; // $1 cost for caramel topping
    }
}

public static void Main(String args[])
{
     Beverage b = new CaramelDecorator(new Espresso());
     System.out.println("Cost of Beverage:" + b.cost());
}
//output--------------
//Cost of Beverage : 4

Though this example does not justify the use of a Decorator Pattern , take this with a pinch of salt and use this to understand what a Decorator Pattern is 🙂 .