装饰器模式
装饰器模式,英文为 decorator模式
场景
假设我们已经有了一个类,可以执行一些功能,但是我们还是希望对这个类的功能做一些增强,基于已有类的功能上,再做一些增强功能,可以做装饰
不使用模式
package com.zhss.designpattern.decorator;
public class DecoratorPatternDemo {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Component decorator = new Decorator(component);
decorator.execute();
}
public interface Component {
void execute();
}
public static class ConcreteComponent implements Component {
public void execute() {
System.out.println("执行基础功能");
}
}
}
使用模式
//其实就是多增加了这个方法
public static class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void execute() {
System.out.println("在执行基础功能之前,执行部分功能增强");
component.execute();
System.out.println("在执行基础功能之后,执行部分功能增强");
}
}
经典实现
- 比如java的io体系,可以一层包装一层,一层包装一层,外面的一层都会对里面的一层进行增强。
- spring的aop,aop这块就是基于动态带来的概念,装饰我们的目标对象,然后加入事务控制、日志打印之类的功能
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果