结构模式-装饰者模式
2022/5/28大约 2 分钟
装饰者模式上指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式
模式结构成员构成:
- 抽象组件(Component):定义一个对象的接口,可以给这些对象动态地添加职责。
- 具体组件(ConcreteComponent):实现或继承抽象组件,并添加基础的行为或属性。
- 装饰者(Decorator):持有一个抽象组件的引用,并定义一个与抽象组件一致的接口。
- 具体装饰者(ConcreteDecorator):实现装饰者接口,并给具体组件对象添加额外的职责。
UML图:
举个例子:小明开了一个茶馆,对外提供白开水,加有茶叶的茶水,加有柠檬的柠檬水等。
抽象组件:
public abstract class Component {
public abstract void execute();
}具体组件:
public class ConcreteComponent extends Component{
@Override
public void execute() {
System.out.println("提供白开水");
}
}装饰者:
public abstract class Decorator extends Component {
/**
* 装饰者,需要组件才能进行装饰操作
*/
public Component component;
public Decorator(Component component) {
this.component = component;
}
}具体装饰者:
public class ConcreteDecorator extends Decorator{
public ConcreteDecorator(Component component) {
super(component);
}
public void before(){
System.out.println("ConcreteDecorator前置操作....加点柠檬");
}
public void after(){
System.out.println("ConcreteDecorator后置操作....");
}
@Override
public void execute() {
before();
component.execute();
after();
}
}测试:
public class TestMain {
public static void main(String[] args) {
Component component = new ConcreteComponent();
component.execute();
Decorator decorator = new ConcreteDecorator(component);
decorator.execute();
}
}结果:
提供白开水
ConcreteDecorator前置操作....加点柠檬
提供白开水
ConcreteDecorator后置操作....装饰器模式和代理模式的区别:
- 代理的目的是全权代理;目标类根本不对外提供服务,全部由代理类来完成;
- 装饰的目的是增强,是辅助;目标类仍然可以自行对外提供服务,装饰器只起增强作用。
装饰者模式经典应用场景-mybatis的缓存
private Cache setStandardDecorators(Cache cache) {
try {
MetaObject metaCache = SystemMetaObject.forObject(cache);
if (this.size != null && metaCache.hasSetter("size")) {
metaCache.setValue("size", this.size);
}
if (this.clearInterval != null) {
// 缓存调度的
cache = new ScheduledCache((Cache)cache);
((ScheduledCache)cache).setClearInterval(this.clearInterval);
}
if (this.readWrite) {
// 缓存序列
cache = new SerializedCache((Cache)cache);
}
// 缓存日志
Cache cache = new LoggingCache((Cache)cache);
// 缓存同步
cache = new SynchronizedCache(cache);
if (this.blocking) {
// 缓存阻塞
cache = new BlockingCache((Cache)cache);
}
return (Cache)cache;
} catch (Exception var3) {
throw new CacheException("Error building standard cache decorators. Cause: " + var3, var3);
}
}