装饰者模式,比前面几种design pattern都复杂,一般情况下并不应该用它。它是为了尽量不修改原有类、接口的情况下为其动态添加功能。但是如果允许修改原有类,我觉得还是应该修改原有类,以达到更好的设计。用了装饰者模式,复杂度增加,不便于后续维护,好处是不需要修改现有的接口啊,不需要动其他使用该类的程序。
下面以一个麦当劳的例子,去麦当劳点一个果汁juice,你需要动态地实现加冰块、糖甚至其他东西。价格也随之变化,相信大家都做过鸡蛋饼或者武大郎烧饼啥的。麦当劳接口和类是原有的组件,我们不希望修改它。
McDonald接口:
public interface McDonald {
double orderJuice();
}
ConcreteMcDonald类:
public class ConcreteMcDonald implements McDonald {
private double price;
public ConcreteMcDonald(double primaryPrice){
this.price=primaryPrice;
}
@Override
public double orderJuice() {
System.out.println("you have ordered a juice");
return price;
}
}
Decorator抽象类:
public abstract class Decorator implements McDonald{
McDonald mcDonald;
public Decorator(McDonald mcDonald){
this.mcDonald=mcDonald;
}
}
IceblocksDecrator类:
public class IceblocksDecrator extends Decorator {
public IceblocksDecrator(McDonald mcDonald){
super(mcDonald);
}
@Override
public double orderJuice() {
double p=mcDonald.orderJuice()+1;
System.out.println("you have added some ice blocks");
return p;
}
}
SugarDecrator类:
public class SugarDecrator extends Decorator {
public SugarDecrator(McDonald mcDonald){
super(mcDonald);
}
@Override
public double orderJuice() {
double p=mcDonald.orderJuice()+3;
System.out.println("you have added some sugar");
return p;
}
}
Client类:
public class Client {
public static void main(String[] args){
McDonald mcDonald=new ConcreteMcDonald(10);
mcDonald=new IceblocksDecrator(mcDonald);
mcDonald=new SugarDecrator(mcDonald);
System.out.print(mcDonald.orderJuice());
}
}
输出:
you have ordered a juice
you have added some ice blocks
you have added some sugar
12.0