本文的内容参考了以下博客和《大话设计模式》:
https://www.cnblogs.com/jzb-blog/p/6717349.html
装饰模式
是一种常见的设计模式,个人理解装饰就是锦上添花之意,即在原有功能基础上增加新功能。
这个模式的设计思想和实现方式比较简单,直接上图。
UML

- Component 为统一接口,也是装饰类和被装饰类的基本类型。
- ConcreteComponent 为具体实现类,也是被装饰类,他本身是个具有一些功能的完整的类。
- Decorator 是装饰类,实现了 Component 接口的同时还在内部维护了一个 ConcreteComponent 的实例,并可以通过构造函数初始化。而 Decorator 本身,通常采用默认实现,他的存在仅仅是一个声明:我要生产出一些用于装饰的子类。而其子类才是赋有具体装饰效果的装饰产品类。
- ConcreteDecorator 是具体的装饰产品类,每一种装饰产品都具有特定的装饰效果。可以通过构造器声明装饰哪种类型的ConcreteComponent,从而对其进行装饰。
以上UML中核心的装饰功能是在 ConcreteDecorator 的 operation() 中实现。
简单代码实现:
//基础接口
public interface Component {
public void operation();
}
//具体实现类
public class ConcretComponent implements Component {
public void operation() {
System.out.println("biubiubiu");
}
}
//装饰类
public class Decorator implements Component {
public Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
this.component.operation();
}
}
//具体装饰类
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
public void operation() {
this.component.operation();
System.out.println("some additional decoration here");
}
}
具体使用的代码如下:
public class DecoratorTest{
public static void Main(){
//使用装饰器
Component component = new ConcreteDecorator(new ConcretComponent());
component.operation();
}
}