设计模式—装饰者模式
通过继承实现子类的行为是在编译时静态决定的,而且所有子类都会继承到相同的行为;而组合可以在运行时动态的进行扩展,所以应该尽量利用组合的方法扩展对象的行为。运行时的扩展远比编译时期的继承威力大
1 装饰者和被装饰者必须是一样的类型,即具有共同的超类。
2 当我们将装饰者与组件组合时,就是在加入新的行为。
3 java I/O中使用了大量的装饰类
4 装饰者模式符合开放——关闭模式:允许扩展,但是不允许修改代码。
Java代码
<span style="font-size: medium;">//超类
package com.quding.mode;
public abstract class Beverage {
private String description = "unknown description";
public String getDescription(){
return description;
}
public abstract double cost();
}
//装饰者超类
package com.quding.mode;
public abstract class Decorator extends Beverage{
public abstract String getDescription();
}
</span>
//具体的子类:
Java代码
<span style="font-size: medium;">package com.quding.mode;
public class Coffee1 extends Beverage{
@Override
public double cost() {
return 2.0; //coffee1 价格2元
}
@Override
public String getDescription() {
return "coffee1";
}
}
//子类2
package com.quding.mode;
public class Coffee2 extends Beverage{
@Override
public double cost() {
return 4.0; //coffee2 价格4元
}
@Override
public String getDescription() {
return "coffee2";
}
}
</span>
装饰者子类:
Java代码
<span style="font-size: medium;">package com.quding.mode;
public class MilkDecorator extends Decorator {
private Beverage mBeverage;
public MilkDecorator(Beverage mBeverage) {
super();
this.mBeverage = mBeverage;
}
@Override
public String getDescription() {
return mBeverage.getDescription() + " , milk";
}
@Override
public double cost() {
return mBeverage.cost() + 1; //加牛奶一元
}
}
//子类2
package com.quding.mode;
public class SugarDecorator extends Decorator {
private Beverage mBeverage;
public SugarDecorator(Beverage mBeverage) {
super();
this.mBeverage = mBeverage;
}
@Override
public String getDescription() {
return mBeverage.getDescription() + " , sugar";
}
@Override
public double cost() {
return mBeverage.cost() + 2; //加糖二元
}
}
</span>
测试代码:
Java代码
<span style="font-size: medium;">package com.quding.mode;
public class MainTest {
public static void main(String[] args) {
System.out.println("要一份加糖的种类为coffee1的咖啡:");
Beverage beverage = new SugarDecorator(new Coffee1());
System.out.println("种类 : " + beverage.getDescription() + "\n价格 : "
+ beverage.cost());
System.out.println("要一份加糖加两份牛奶的种类为coffee2的咖啡:");
beverage = new SugarDecorator(new MilkDecorator(new MilkDecorator(
new Coffee2())));
System.out.println("种类 : " + beverage.getDescription() + "\n价格 : "
+ beverage.cost());
}
}
</span>
总结:以上简单的几个类体现了装饰者模式的精髓。以后当使用继承时要考虑能否使用装饰者代替,扩展代码的弹性。
作者“quding0308的博客”
补充:软件开发 , Java ,