1、含义
装饰模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案
2、结构
装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰模式可以在不使用创造更多子类的情况下,将对象的功能加以扩展
3、角色
- 抽象构件角色:给出一个抽象接口,以规范准备接收附加责任的对象。
- 具体构件角色:定义一个将要接收附加责任的类。
- 装饰角色:持有一个构件对象的实例,并定义一个与抽象构件接口一致的接口。
- 具体装饰角色:负责给构件对象“贴上”附加的责任。
咖啡例子:
//抽象构件角色
public abstract class Coffee {
public String coffeeName;
public abstract Integer money();
}
//具体构件角色
public class IrishCoffee extends Coffee{
public IrishCoffee() {
this.coffeeName="爱尔兰咖啡";
}
@Override
public Integer money() {
// TODO Auto-generated method stub
return 2;
}
}
//装饰角色
public abstract class Batching extends Coffee{
public abstract void getName(String coffeeName);
}
//具体装饰角色
public class Sugar extends Batching{
Coffee coffee;
public Sugar(Coffee coffee) {
this.coffee = coffee;
this.getName(coffee.coffeeName);
}
@Override
public void getName(String coffeeName) {
this.coffeeName ="加糖" + coffeeName ;
}
@Override
public Integer money() {
return this.coffee.money() + 1;
}
}