装饰者模式
一、什么是装饰者模式
在不改变原有功能的基础上附加功能,相比生成子类更灵活。
二、装饰者模式应用场景
- 动态的给一个对象添加或者撤销功能。
- 多级缓存设计
- mybatis中一级与二级缓存
- IO流
三、装饰者模式定义
(1)抽象组件:定义一个抽象接口,来规范准备附加功能的类
(2)具体组件:将要被附加功能的类,实现抽象构件角色接口
(3)抽象装饰者:持有对具体构件角色的引用并定义与抽象构件角色一致的接口
(4)具体装饰:实现抽象装饰者角色,负责对具体构件添加额外功能。
装饰者模式类图
四、装饰者模式优缺点
优点:可以不改变原有对象的情况下动态扩展功能,可以使扩展的多个功能按想要的顺序执行,以实现不同效果。
缺点:更多的类,使程序复杂
五、装饰者代码实现
定义一个接口
public interface GatewayComponent {
/**
* 定义共同附加行为方法标准..
*/
void service();
}
定义被装饰角色
public class BasicComponentGateway implements GatewayComponent {
@Override
public void service() {
System.out.println("第一步>>> 网关中获取基本的操作...实现");
}
}
定义抽象装饰角色
public class AbstractDecorator implements GatewayComponent {
public AbstractDecorator(GatewayComponent gatewayComponent) {
this.gatewayComponent = gatewayComponent;
}
public GatewayComponent gatewayComponent;
@Override
public void service() {
if (gatewayComponent != null)
gatewayComponent.service();
}
}
定义具体装饰角色
public class LogDecorator extends AbstractDecorator {
public LogDecorator(GatewayComponent gatewayComponent) {
super(gatewayComponent);
}
@Override
public void service() {
super.service();
System.out.println("第二步>>> 网关中新增日志收集..");
}
}
public class LimitDecorator extends AbstractDecorator {
public LimitDecorator(GatewayComponent gatewayComponent) {
super(gatewayComponent);
}
@Override
public void service() {
super.service();
System.out.println("第三步>>> 网关中新增API接口的限流..");
}
}
使用工厂获取装饰类
public class FactoryGateway {
public static GatewayComponent getGatewayComponent() {
return new LimitDecorator(new LogDecorator(new BasicComponentGateway()));
}
public static void main(String[] args) {
GatewayComponent gatewayComponent = FactoryGateway.getGatewayComponent();
gatewayComponent.service();
}
}
执行结果
Connected to the target VM, address: '127.0.0.1:56931', transport: 'socket'
第一步>>> 网关中获取基本的操作...实现
第二步>>> 网关中新增日志收集..
第三步>>> 网关中新增API接口的限流..
Disconnected from the target VM, address: '127.0.0.1:56931', transport: 'socket'
Process finished with exit code 0
六、Java I/O 中的装饰者模式
它基于字符流(InputStream/OutputStream) 和 字节流(Reader/Writer)作为基类,下面画出InputStream、Reader的
抽象构造角色 Reader
FilterReader 抽象的装饰类
七、责任链与装饰模式区别
责任链实现原理
每个被调用者 都持有下一个 被调用者 的引用,客户端只需要发起一次调用即可。
装饰的实现原理
持有被装饰的对象,并具备 被装饰者 的行为,对其行为进行补充增强