The decorator pattern is used to add capabilities to objects dynamically (that is, at run time). Normally the object will have its capabilities fixed when you write the class. But an important point is that the functionality of the object is extended in a way that is transparent to the client of the object because it implements the same interface as the original object delegates responsibility to the decorated object.
The decorator pattern works in scenarios where there are many optional functionality that an object may have. Without the decorator pattern you will have to create a different class for each object-option configuration. One example that is pretty useful comes from the Head First Design Patterns book by O'reilly. It uses a coffee shop example that sounds just like StarBucks.
So you have the basic coffee with a method like cost.
public double cost(){
return 3.45;
}
Then th ecustomer can add cream which cost 0.35 so you now create a CoffeeCream class with the cost method:
public double cost(){
return 3.80;
}
Then the customer may want Mocha which cost 0.5, and they may want Mocha with Cream or Mocha without Cream. So you create classes CoffeeMochaCream and CoffeeMocha. Then a customer wants double cream so you create a class CoffeeCreamCream...etc etc. What you end up with is class explosion. Please excuse the poor example used. Its a bit late and I know its trivial but it does express the point.
Instead you can create an Item abstarct class with an abstract cost method:
public abstract class Item{
public abstract double cost();
}
And you can create a concrete Coffee class that extends Item:
public class Coffee extends Item{
public double cost(){
return 3.45;
}
}
Then you create a CoffeeDecorator that extend the same interface and contain an Item.
public abstract class CoffeeDecorator extends Item{
private Item item;
...
}
Then you can create concrete decorators for each option:
public class Mocha extends CoffeeDecorator{
public double cost(){
return item.cost() + 0.5;
}
}
Notice how the decorator does not care what type of object it is wrapping just as long as its an Item? It uses the cost() of the item object and simply adds its own cost.
public class Cream extends CoffeeDecorator{
public double cost(){
return item.cost() + 0.35;
}
}
Now it is possible for a large number of configurations with these few classes:
e.g.
Item drink = new Cream(new Mocha(new Coffee))); //Mocha with cream
or
Item drink = new Cream(new Mocha(new Cream(new Coffee))));//Mocha with double cream
And so on.