Tuesday, March 15, 2016

Design Pattern - 3 - Decorator Pattern



Decorator Pattern - Attaches additional responsibilities to an object dyanmically.
Decorators  provide a flexible alternative to subclassing for extending functionality.

Example: Take the case of veg. pizza being ordered. Customer wants to add extra cheese as topping.
Here the veg. pizza is the basic class and cheese is the decorator class. Cheese class decorates the veg. pizza.
Similarly, if user decides to add some extra jalepenos. Then, jalepeno is a decorator class.

Code:
class VegPizza extends Pizza {
  // description of VegPizza 
   String topping; 
   addTopping(){
       topping = topping+"veg";
   }   
}

abstract class Toppings extends Pizza {
 
}

class CheeseTopping extends Toppings {
   Pizza pizza;
   CheeseTopping(Pizza pizza){
      this.pizza= pizza;
   }
    addTopping(){
       pizza.topping=pizza.topping + "cheese";       
   }
}

class JalepenoTopping extends Toppings {
   Pizza pizza;
   JalepenoTopping(Pizza pizza){
       this.pizza= pizza;   
   }
   addTopping(){
            pizza.topping=pizza.topping + "Jalepeno";       
   }
}

class MainClass{
  public static void main(String args[]){
   Pizza vegPizza = new VegPizza();
   CheeseTopping topping1= new CheeseTopping(vegPizza);
   JalepenoTopping topping2 = new JalepenoTopping(vegPizza);
   System.out.print("Toppings added:+"vegPizza.toppings);   
 }
}

Design Principle: Classes should be open for extension, but closed for modification.

Design Principles so far:
1) Encapsulate what varies
2) Favor composition over inheritance.
3) Program to interfaces, not implementations.
4) Strive for loosely coupled designs between objects that interact.
5) Classes should be open for extension, but closed for modification.

The downside of the decorator pattern is - a lot of small classes(decorator) can get added up making it difficult to understand the design.
However, the benefit lies in the fact the the client or the base class not being aware that it is being decorated upon.

No comments: