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
No comments:
Post a Comment