1.定义#
动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。装饰模式是继承机制的一种扩充。装饰器抽象类实则为一个代理类,负责为被装饰者添加功能。首先具体装饰者通过super方法告诉抽象装饰者本具体装饰者是哪一个,然后通过重写抽象装饰者的执行方法,在使用super执行传入本装饰者的装饰者之前或者之后加入一些处理逻辑。达到扩充之前逻辑的目的。
2.类图#
3.实现#
3.1抽象构件##
public abstract class Component {
public abstract void operate();
}
3.2具体构件##
public class ConcreteComponent extends Component{
@Override
public void operate() {
//被装饰者,具体的事物执行者
System.out.println("do somthing");
}
}
3.3抽象装饰者##
public class Decorator extends Component{
private Component component = null;
//通过构造函数传递被修饰者
public Decorator(Component _component) {
this.component = _component;
}
@Override
public void operate() {
this.component.operate();
}
}
3.4具体装饰者##
public class ConcreteDecorator1 extends Decorator {
public ConcreteDecorator1(Component _component) {
super(_component);
}
private void method1() {
System.out.println("method1 修饰");
}
@Override
public void operate() {
method1();
super.operate();
}
}
public class ConcreteDecorator2 extends Decorator {
public ConcreteDecorator2(Component _component) {
super(_component);
}
private void method2(){
System.out.println("method2 修饰");
}
@Override
public void operate() {
super.operate();
this.method2();
}
}
3.5客户端##
public class Client {
public static void main(String args[]) {
Component component = new ConcreteComponent();
component = new ConcreteDecorator1(component);
component = new ConcreteDecorator2(component);
component.operate();
}
}