1.什么是装饰模式
在不改变原有对象的基础上实现增强
2.应用场景
io流中FilterReader()
3.装饰模式实现
链接:https://pan.baidu.com/s/1VTv9oJ1W8wuEXFWdZIlcRQ
提取码:yyon
1)定义共同的方法标准
/**
* 装饰接口标准
* */
public abstract class GatewayComponent {
/**
* 定义共同附加行为方法标准
*/
public abstract void service();
}
2)被装饰类
import com.demo.GatewayComponent;
/**
* 被装饰类
*/
public class BasicComponentGateway extends GatewayComponent {
public void service() {
System.out.println("第一步>>> 网关中获取基本的操作...实现");
}
}
3)定义抽象装饰类
/**
* 定义抽象装饰类
*/
public class AbstractDecorator extends GatewayComponent {
public GatewayComponent gatewayComponent;
public AbstractDecorator(GatewayComponent gatewayComponent) {
this.gatewayComponent = gatewayComponent;
}
public void service() {
if (gatewayComponent != null) {
gatewayComponent.service();
}
}
}
4)具体装饰类
import com.demo.AbstractDecorator;
import com.demo.GatewayComponent;
/**
* 具体装饰类
*/
public class LogDecorator extends AbstractDecorator {
public LogDecorator(GatewayComponent gatewayComponent) {
super(gatewayComponent);
}
@Override
public void service() {
super.service();
System.out.println("第二步>>> 网关中新增日志收集..");
}
}
import com.demo.AbstractDecorator;
import com.demo.GatewayComponent;
/**
* 具体装饰类
*/
public class LimitDecorator extends AbstractDecorator {
public LimitDecorator(GatewayComponent gatewayComponent) {
super(gatewayComponent);
}
@Override
public void service() {
super.service();
System.out.println("第三步>>> 网关中新增API接口的限流..");
}
}
5)装饰工厂类
import com.demo.GatewayComponent;
import com.demo.impl.BasicComponentGateway;
import com.demo.impl.LimitDecorator;
import com.demo.impl.LogDecorator;
/**
* 装饰工厂类
*/
public class FactoryGateway {
public static GatewayComponent getGatewayComponent() {
return new LimitDecorator(new LogDecorator(new BasicComponentGateway()));
}
}
6)测试类
import com.demo.GatewayComponent;
import com.demo.factory.FactoryGateway;
public class Test {
public static void main(String[] args) {
GatewayComponent gatewayComponent = FactoryGateway.getGatewayComponent();
gatewayComponent.service();
}
}