标签:
装饰者模式:动态的将责任附加到对象上,若要扩展功能,装饰者提供了更有弹性的替代方案。
l 调料价格变动会改变原有代码
l 新增调料,除了加上新增方法外,还需要改变超类中的Cost()方法
l 依赖继承,子类将继承一些对自身并不合适的方法
l 部分需求无法满足:如双倍摩卡咖啡
l 违反了开放—关闭原则
Beverage类(抽象组件)
1 public abstract class Beverage 2 { 3 public string description = "Unknown Beverage"; 4 public abstract string GetDescription(); 5 public abstract double Cost(); 6 }
Condiment(调料)基类(继承自Beverage基类,抽象装饰者)
public abstract class CondimentDecorator extends Beverage { public abstract string GetDescription(); }
饮料类(继承Beverage基类,具体组件)
public class Espresso extends Beverage { public Espresso() { description = "Espresso";//设置饮料的表述,description继承自Beverage类的实例变量 } public double Cost() { return 1.99; } public string GetDescription() { return description; } }
调料类(装饰者)
1 public class Mocha extends CondimentDecorator 2 { 3 Beverage beverage; 4 public Mocha(Beverage beverage) 5 { 6 this.beverage = beverage; 7 } 8 9 public string GetDescription() 10 { 11 return beverage.GetDescription() + ",Mocha"; 12 } 13 public double Cost() 14 { 15 return 0.2 + beverage.Cost(); 16 } 17 }
测试代码
1 Beverage beverage1 = new DarkRoase(); 2 beverage1 = new Mocha(beverage1); 3 beverage1 = new Mocha(beverage1); 4 beverage1 = new Whip(beverage1);
标签:
原文地址:http://www.cnblogs.com/HectorHou/p/5979188.html