对于一个对象,不改变原代码的情况下,增添一些额外属性或功能。
角色:
抽象构件: 目标类的接口/父类
具体构件: 目标类
抽象装饰器:继承抽象构件(同目标类实现同一接口),并注入具体构件的实例,便可调用目标类的原方法。
具体装饰器:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任(使用抽象装饰调用目标类的方法之前/之后,添加自己的功能)。
过程:
现在有个接口(抽象构件),它有个实现类,即目标类(具体构件),需要对其方法增强。
//抽象构件角色
interface Component {
public void operation();
}
//具体构件角色
class ConcreteComponent implements Component {
public ConcreteComponent() {
System.out.println("创建具体构件角色");
}
public void operation() {
System.out.println("调用具体构件角色的方法operation()");
}
}
定义抽象装饰角色,该类也实现抽象构件,并注入具体构件,这样就可以调用具体构件的方法了
//抽象装饰角色
class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
继承抽象装饰角色,开始增强
//具体装饰角色
class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
public void operation() {
super.operation();
addedFunction();
}
public void addedFunction() {
System.out.println("为具体构件角色增加额外的功能addedFunction()");
}
}
可以实现多个装饰器,在不同场景下选择不同的装饰器;
也可以叠加,比如使用装饰器1装饰原对象,再用装饰器2增强装饰器1。

被折叠的 条评论
为什么被折叠?



