设计模式之Decorator Pattern

  在这个模式中把面向对象的好处得到了很好的体现。在类设计的时候可能会遇到组合爆炸的情况,比如《head first》中咖啡的例子。在不同的咖啡中添加不同调料的时候价格是不一样的,如果有10种调料,那么一杯咖啡的种类就由2^10=1024。但是我们不可能设计1024个类来做,就算做了维护起来也是很恐怖的。

  装饰者模式很好的利用继承来解决了这个问题,反正都是一杯咖啡,不过是在向里面加东西而已。如果只是要求咖啡的价格用面向过程的写成for+switch就可以了。在创造类型的过程中继承给人的感觉有点像这个循环的作用。下面是一个装饰者模式的例子:

interface coffee{
int cost();
}
class a implements coffee{
coffee coffee;
public a(coffee coffee){
this.coffee = coffee;
}
public int cost() {
if(coffee == null)
return 1;
else
return coffee.cost()+1;
}
}

class b implements coffee{
coffee coffee;
public b(coffee coffee){
this.coffee = coffee;
}
public int cost() {
if(coffee == null)
return 2;
else
return coffee.cost()+2;
}
}

public class Test {
public static void main(String[] arg){
coffee coffee = new a(null);
System.out.println(coffee.cost());
coffee = new b(coffee);
System.out.println(coffee.cost());
}
}
原文地址:https://www.cnblogs.com/ggzwtj/p/2224975.html