浏览 1821 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-06-23
最后修改:2009-06-23
public abstract class Beverage { String description = "unknown beverage"; public String getDescription() { return description; } public abstract double cost(); } 装饰者抽象类 public abstract class CondimentDecorator extends Beverage { public abstract String getDescription(); } 浓咖啡 public class Espresso extends Beverage { public Espresso(){ description = "Espresso"; } @Override public double cost() { // TODO Auto-generated method stub return 1.99; } } 佐料(装饰者)摩卡类 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(); } } 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()); } } 设计原则 对扩展开放,对修改关闭 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |