动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。
public class Decorator_Main {
public static void main(String[] args) {
Cake cake = new AppleCakeDecorator(new AppleCake());
cake.getDesc();
cake.cost();
}
}
abstract class Cake {
protected abstract String getDesc();
protected abstract Integer cost();
}
class AppleCake extends Cake{
@Override
protected String getDesc() {
System.out.println("我是一只普通的苹果蛋糕");
return "apple";
}
@Override
protected Integer cost() {
System.out.println("苹果蛋糕...五块钱");
return 5;
}
}
class AppleCakeDecorator extends Cake {
private Cake cake;
public AppleCakeDecorator(Cake cake) {
this.cake = cake;
}
@Override
protected String getDesc() {
System.out.println(cake.getDesc()+":加上包装盒喽");
return "banana_decorator";
}
@Override
protected Integer cost() {
System.out.println("一共花费:"+(cake.cost() + 2));
return cake.cost() + 2;
}
}