lundi 13 février 2017

Decorator Design Pattern Example Understanding

I read one example of Decorator Design Pattern .I understood this design pattern that this modify the behaviour of one particular instance dynamically.The example which i have given below is also understandable.The point which I did not understand is that when I call c.getCost() on milk object returns 1.5. Only coffee method getcost returns 1 but from where c.getCost on milk returns 1.5.

Can anyone please explain the link between the milk class and simplecoffe clas and how the execution of method getCost() flows when called with milk object.How the getCost() method returns 1.5 ?

//Decorator Design Pattern

interface coffee
{
public double getCost();
public String getIngredients();
}

 class simplecoffee implements coffee
{
   public double getCost()
   {
      return 1;
   }

   public String getIngredients()
   {
     return "Coffee";
   }
}

 abstract class coffeedecorator implements coffee
{
protected coffee decoratedcoffee;
protected String ingredientseparator=":";

public coffeedecorator(coffee decoratedcoffee)
{

    this.decoratedcoffee=decoratedcoffee;
}

 public double getCost()
   {
  return decoratedcoffee.getCost();
   }

    public String getIngredients()
    {
     return decoratedcoffee.getIngredients();
    }
  }

 class milk extends coffeedecorator
{

public milk(coffee decoratedcoffee)
{

   super(decoratedcoffee);
   System.out.println("Milk Constructor");
}
    public double getCost()
   {
  return super.getCost()+0.5;
   }

    public String getIngredients()
    {
     return super.getIngredients()+ingredientseparator+"milk";
     }
 }

public class decorator
{
 public static void main(String[] ar)
 {
System.out.println("calling simplecoffee in main");
coffee c=new simplecoffee();
System.out.println("Cost:"+c.getCost());
c=new milk(c);
System.out.println("Cost:"+c.getCost());
 }
}

Aucun commentaire:

Enregistrer un commentaire