Friday, 22 April 2016

Decorator Design Pattern

Decorator Design Pattern

When all entities contribute to achieve a bigger role, use Decorator Design Pattern.




public abstract class Pizza {
      String description = "no particular";
      public String getDescription(){
            return description;
      }
    public abstract String getCost(){
            return description;
      }
}

public class WheatBread extends Pizza {
      String description = “Wheat Pizza”;
      public String getDescription(){
            return description;
      }
    public String getCost(){
            return 0.2;
      }
}

public class OlivesToppings extends Toppings{
      String description = “Olives Toppings”;
      public String getToppingsDescription(){
            return description;
      }
    public String getCost(){
            return super.getCost()+0.05;
      }
}

public class OnionToppings extends Toppings{
      String description = “Onion Toppings”;
      public String getToppingsDescription(){
            return description;
      }
    public String getCost(){
            return super.getCost()+0.03;
      }
}

So if someone orders WheatBread pizza with Olives and Onion toppings, we use
Pizza pizza = new WheatBread();
pizza = new OlivesToppings(pizza);
pizza = new OnionToppings(pizza);
//So output will be
pizza.getCost();   // Prints :: 0.28
pizza.getDescription();
// Prints :: Wheat Pizza with Olives Toppings with Onion Toppings

One great example is java.io classes



1.     Designs using this pattern often result in a large number of small classes.
2.     It attaches additional responsibilities to an object dynamically.
3.     Privies alternative to sub-classing.
a.      So if we did use subclasses here, we would end up creating classes for all permutations & combinations of pizza breads and toppings.
4.     Plays with the idea of wrapping objects with any number of decorators.
5.     It follows “Open-Close” principle of design pattern

a.      This principle advices that a code should be open for extension but close for modification.

Code link : https://github.com/sksumit1/DesignPatterns

No comments:

Post a Comment