Coffee and Decorator Pattern

public abstract class Beverage{
  string description
="Unknow Beverage";

  
public String getDescription(){
      
return description;
  }

  
public acstract double cost();
}


public abstract class CondimentDecorator extends Beverage{
  
public abstratct String getDescription();
}


public class Espresso extents Beverage{
   
public Espresso(){
      description
="Espresso";
   }

    
public double cost(){
        
return 1.99;
    }

}

 
public class HouseBlend extends Beverage{
   
public HouseBlend(){
        description
="House Blend Coffee";
   }

   
public double cost(){
       
return .89;
    }

}

Coding Condiments:
public class Mocha extends CondimentDecorator{
     Beverage beverage;

     
public Mocha(Beverage beverage){
       
this.beverage=beverage;
      
// An instance variable to hold the beverage we are wrapping
      
// A way to set this instance variable to the object we are 
      
// wrapping . Here, we are going to pass the beverage we are 
      
// wrappking to the decorator's constructor
     }

      
     
public String getDescription(){
        
return beverage.getDescription()+",Mocha";
     }

      
     
public double cost(){
        
return .20+beverage.cost();
     }

}

Test
public class StarBuzzCoffee{
  
   
public static void main(String arg[]){
       
        Beverage beverage
=new DarkRoast();
        beverage 
=new Mocha(beverage);
        beverage 
=new Whip(beverage);
        System.out.println(beverage.getDescription()    
+"$"+beverage.cost());
     }

}

      

 

posted on 2007-06-15 18:08  ewan  阅读(160)  评论(0)    收藏  举报

导航