Thursday, 2 January 2014

Decorator Design pattern - Implementation [Pizza]



Click here to watch in Youtube : https://www.youtube.com/watch?v=Xz2eKQy9kBU

Click the below Image to Enlarge
Decorator Design pattern - Implementation [Pizza]

Decorator Design pattern - Implementation [Pizza] - Class Diagram



































Pizza.java

public interface Pizza
{
public String makePizza();
}

PlainPizza.java

public class PlainPizza implements Pizza
{

@Override
public String makePizza()
{
return "Plain Pizza ";
}
}

PizzaDecorator.java

abstract class PizzaDecorator implements Pizza
{

protected Pizza pizza;

public PizzaDecorator( Pizza pizza )
{
this.pizza = pizza;
}

public String makePizza()
{
return pizza.makePizza();
}
}

ChickenPizzaDecorator.java

public class ChickenPizzaDecorator extends PizzaDecorator
{

public ChickenPizzaDecorator( Pizza pizza )
{
super(pizza);
}

public String makePizza()
{
return pizza.makePizza() + addChickenAndCheese();

}

private String addChickenAndCheese()
{
return ",Chicken and Cheese added";
}
}

VegPizzaDecorator.java

public class VegPizzaDecorator extends PizzaDecorator
{

public VegPizzaDecorator( Pizza pizza )
{
super(pizza);
}

public String makePizza()
{
return pizza.makePizza() + addVegetableAndCheese();
}

private String addVegetableAndCheese()
{
return ",Vegetable and Cheese added";

}
}

DecoratorClient.java

public class DecoratorClient
{

public static void main( String args[] )
{
PlainPizza plainPizzaObj = new PlainPizza();
String plainPizza = plainPizzaObj.makePizza();
System.out.println(plainPizza);

String chickenPizza = new ChickenPizzaDecorator(plainPizzaObj).makePizza();
System.out.println("\n'" + chickenPizza + "' using ChickenPizzaDecorator");

String vegPizza = new VegPizzaDecorator(plainPizzaObj).makePizza();
System.out.println("\n'" + vegPizza + "' using VegPizzaDecorator");

}

}

Output

Plain Pizza 

'Plain Pizza ,Chicken and Cheese added' using ChickenPizzaDecorator

'Plain Pizza ,Vegetable and Cheese added' using VegPizzaDecorator


See also:

  • Decorator Design pattern - Introduction
  • Decorator Design pattern - Real Time Example [Dosa]
  • Decorator Design pattern - Real Time Example [Ice Cream]
  • Decorator Design pattern - Real Time Example [Pizza]
  • Decorator Design pattern - Real Time Example [Car]
  • Decorator Design pattern - Class Diagram
  • Decorator Design pattern - Sequence Diagram
  • Decorator Design pattern - Implementation [Dosa]
  • Decorator Design pattern - Implementation [Pizza]
  • Decorator Design pattern - Implementation [Ice Cream]
  • Decorator Design pattern - Implementation [Car]
  • Decorator Design pattern - Implementation [Shape]
  • Decorator Design pattern - Key Points
  • All Design Patterns Links
  • No comments:

    Post a Comment

    Google+ Followers

    Google+ Badge