装饰模式:
装饰模式(Decorator Pattern) :动态地给一个对象增加一些额外的职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活。其别名也可以称为包装器(Wrapper、Decorator)。根据翻译的不同,装饰模式也有人称之为“油漆工模式”,它是一种对象结构型模式。
UML结构图如下:
Component 是抽象构件,定义一个对象接口,可以给这些对象动态的添加职责;
ConcreteComponent定义一个具体对象,实现 Component;
Decorator : 是装饰抽象类,实现接口, 作为所有装饰类的父类。
ConcreteDecorator: 是Decorator子类,具体装饰对象;
场景:
我们以汽车为例, 定义接口Car:【对应:Component 】
public interface Car {
void operation();
}
新建汽车的实现类, 比亚迪: BYDCar 【对应:ConcreteComponent】:
public class BYDCar implements Car{
@Override
public void operation() {
System.out.print("比亚迪-汉");
}
}
现在汽车有了,我们要给汽车进行一下改装,而不改变原来的对象, 抽象类:CarDecorator 【对应:Decorator】
abstract class CarDecorator implements Car{
Car component;
public CarDecorator(Car component) {
this.component = component;
}
}
给原有汽车添加一个 尾翼 CarTailDecorator 【对应:ConcreteDecorator】:
public class CarTailDecorator extends CarDecorator{
public CarTailDecorator(Car component) {
super(component);
}
@Override
public void operation() {
System.out.print("加尾翼(");
component.operation();
System.out.print(")");
}
}
给原有汽车添加一个天窗 CarSkylightDecorator【对应:ConcreteDecorator】:
public class CarSkylightDecorator extends CarDecorator{
public CarSkylightDecorator(Car component) {
super(component);
}
@Override
public void operation() {
System.out.print("加天窗(");
component.operation();
System.out.print(")");
}
}
那么, 现在把 尾翼、天窗装饰到 比亚迪上, 测试类如下 Test :
public class Test {
public static void main(String[] args) {
// 原对象
Car car = new BYDCar();
// 装饰
car = new CarTailDecorator(new CarSkylightDecorator(car));
car.operation();
}
}
执行后打印如下:
装饰者有点:
- 不改变原有对象的情况下给一个对象扩展功能
- 使用不同的组合可以实现不同的效果
- 符合开闭原则
装饰者模式在源码中的应用:
Mybatis 缓存实现: