一、装饰者模式定义:通过组合和委托,动态的扩展被装饰者的行为。
二、设计方法:装饰者和被装饰者实现同样的接口,装饰者成员变量中包含被装饰者对象,通过在调用的被装饰者某个方法前面或者后面加上自己的行为,从而达到扩展的目的。可以用无数个装饰者包装同一个组件。装饰者会导致设计中出现很多小对象,如果过度使用,会让程序变复杂。
三、体现的思想:开放—封闭原则(对扩展开发,对修改关闭)
四、具体案例——饮料的设计
五、程序设计
1)Beverage接口和CondimentDecorator接口
public abstract class Beverage {
private String description="unknown beverage";
public String getDescrition(){
return this.description;
}
public abstract double cost();
}
public abstract class CondimentDecorator extends Beverage {
public abstract String getDescription();
}
2)Beverage实现类
public class HouseBlend extends Beverage {
@Override
public double cost() {
return 12.6;
}
public String getDescrition(){
return "houseblend";
}
}
public class DarkRoast extends Beverage {
@Override
public double cost() {
return 29.6;
}
public String getDescrition(){
return "DarkRoast";
}
}
3)CondimentDecorator实现类
public class Milk extends CondimentDecorator {
private Beverage beverage;
public Milk(Beverage beverage){
this.beverage=beverage;
}
@Override
public String getDescription() {
return "milk,"+beverage.getDescrition();
}
@Override
public double cost() {
return 2.22+beverage.cost();
}
}
public class Mocha extends CondimentDecorator {
private Beverage beverage;
public Mocha(Beverage beverage){
this.beverage=beverage;
}
@Override
public String getDescription() {
return "mocha,"+beverage.getDescrition();
}
@Override
public double cost() {
return 1.11+beverage.cost();
}
}
4)测试类
@Test
public void decorateTest(){
Beverage beverage=new HouseBlend();
System.out.println("cost1 is:"+beverage.cost());
//先用Mocha来装饰
beverage=new Mocha(beverage);
System.out.println("cost2 is:"+beverage.cost());
//再用Milk来装饰
beverage=new Milk(beverage);
System.out.println("cost3 is:"+beverage.cost());
}
输出结果为:
cost1 is:12.6
cost2 is:13.71
cost3 is:15.93