Attach additional responsibilities to an object dynamically keeping the same interface.Decorators provide a flexible alternative to subclassing for extending functionality.
本篇博客属于《Java设计模式》系列之一,内容主要借鉴于 秦小波的著作《设计模式之禅》,在理解过程中可能还参考其他博主的知识,最后整理成自己的学习笔记,在此分享给大家。由于本人知识和能力有限,博客中有错误或者理解偏差的地方,还望大佬们多多指点,感谢不尽。(目前处于实习阶段,设计模式配合个人的实际经验更下饭,暂时更新最常见设计模式9+1篇。立个flag,将来一定会补齐)–2020.11.22
定义
动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。
装饰模式的通用类图:
- Component:是一个类或者抽象类,定义最核心的对象。
- ConcreteComponent:是最核心、最原始、最基本的接口或者抽象类的实现,也是被装饰的对象。
- Decorator:一般是一个抽象类,实现接口或抽象方法,它里面不一定有抽象方法,但是它的属性里必定有一个Private变量指向Component对象。
- ConcreteComponent:具体装饰的角色,可以有多个,把最核心最原始最基本的东西装饰成其他东西。
抽象构件:
public abstract class Component {
// 抽象方法
public abstract void operate();
}
具体构件:
public class ConcreteComponent extends Component{
// 具体实现
@Override
public void operate() {
System.out.println("do something");
}
}
抽象装饰者:
public abstract class Decorator extends Component{
private Component component = null;
public Decorator(Component _component){
this.component = _component;
}
@Override
public void operate() {
this.component.operate();
}
}
具体装饰类:
public class ConcreteDecorator1 extends Decorator{
public ConcreteDecorator1(Component _component) {
super(_component);
}
private void method1(){
System.out.println("method1 修饰");
}
@Override
public void operate(){
this.method1();
super.operate();
}
}
public class ConcreteDecorator2 extends Decorator {
public ConcreteDecorator2(Component _component) {
super(_component);
}
private void method2(){
System.out.println("method2修饰");
}
public void operate(){
super.operate();
this.method2();
}
}
场景类
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
// 第一次修饰
component = new ConcreteDecorator1(component);
// 第二次修饰
component = new ConcreteDecorator2(component);
// 修饰后运行
component.operate();
}
}
输出结果:
method1 修饰
do something
method2修饰
优缺点
优点:
- 装饰类和被装饰类可以独立发展,而不会互相耦合
- 装饰模式是继承模式的一个替代方案。
- 装饰模式可以动态地扩展一个实现类的功能
缺点: 多层装饰是复杂的,尽量减少装饰的数量,降低系统的复杂度。
使用场景
- 需要扩展一个类的功能,或给一个类增加附加功能
- 需要动态地给一个对象增加功能,这些功能可以再动态地撤销
- 需要为一批兄弟类进行改装或加装功能
装饰和继承的区别
继承是静态地给类增加功能,而装饰模式是动态地增加功能。装饰模式的扩展性非常好。三个继承关系Father、Son、GrandSon三个类,我要在Son类上增强功能怎么办?SonDecorator
在框架中的应用
- Mybatis中使用装饰实现缓存