动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
例子:
被装饰的接口:
public interface Cake {
public float cost();
}
接口的实现类:
public class MilkCake implements Cake{
@Override
public float cost() {
return 100f;
}
}
装饰者抽象类:
public abstract class CakeDecorator implements Cake{
}
装饰者的实现类
public class Chocolate extends CakeDecorator{
private Cake cake;
public Chocolate(Cake cake) {
this.cake = cake;
}
@Override
public float cost() {
float chocolatePrice = 25f;
return cake.cost() + chocolatePrice;
}
}
public class Berry extends CakeDecorator {
private Cake cake;
public Berry(Cake cake) {
this.cake = cake;
}
@Override
public float cost() {
float berryPrice = 5f;
return cake.cost() + berryPrice;
}
}
测试类:
public class Test {
public static void main(String[] args) {
MilkCake mc = new MilkCake();//牛奶蛋糕
System.out.println(mc.cost());
Berry b = new Berry(mc);//牛奶草莓蛋糕
System.out.println(b.cost());
Chocolate c = new Chocolate(b);//牛奶草莓巧克力蛋糕
System.out.println("付款:" + c.cost());
}
}