WEB开发网
开发学院软件开发Java hand first 设计模式 - 装饰者模式 阅读

hand first 设计模式 - 装饰者模式

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示:所有饮料抽象类 Java代码publicabstractclassBeverage{Stringdescription="unknownbeverage";publicStringgetDescription(){returndescription;}publicabstractdoublecost

所有饮料抽象类

Java代码   

public abstract class Beverage { 
 
 String description = "unknown beverage"; 
 
 public String getDescription() { 
 return description; 
 } 
 
 public abstract double cost(); 
 
}

装饰者抽象类

Java代码   

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

浓咖啡

Java代码   

public class Espresso extends Beverage { 
 
 public Espresso(){ 
 description = "Espresso"; 
 } 
 @Override 
 public double cost() { 
 // TODO Auto-generated method stub 
 return 1.99; 
 } 
 
}

佐料(装饰者)摩卡类

Java代码   

public class Mocha extends CondimentDecorator { 
 
 Beverage beverage; 
 
 public Mocha(Beverage beverage){ 
 this.beverage = beverage; 
 } 
 @Override 
 public String getDescription() { 
 // TODO Auto-generated method stub 
 System.out.println(beverage.getDescription()); 
  
 return beverage.getDescription()+",Mocha"; 
 } 
 
 @Override 
 public double cost() { 
 // TODO Auto-generated method stub 
 return .20 +beverage.cost(); 
 } 
 
}

Java代码   

public class StarbuzzCoffee { 
 
 /** 
 * @param args 
 */ 
 public static void main(String[] args) { 
 // TODO Auto-generated method stub 
 //单纯的咖啡 
 Beverage beverage = new Espresso(); 
  
          //加入摩卡的咖啡 
 beverage = new Mocha(beverage); 
  
 System.out.println(beverage.getDescription()+" $ "+beverage.cost()); 
} 
 
}

设计原则

对扩展开放,对修改关闭

Tags:hand first 设计模式

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接