代码详解:【设计模式】Java 设计模式之装饰者模式(Decorator)_java 装饰者模式-CSDN博客
java
// 抽象构件角色
public interface Component {
void operation();
}
// 具体构件角色
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("执行具体构件对象的操作");
}
}
// 装饰角色
public class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
if (component != null) {
component.operation();
}
}
}
// 具体装饰角色A
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedFunctionA();
}
public void addedFunctionA() {
System.out.println("为构件对象添加功能A");
}
}
// 具体装饰角色B
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedFunctionB();
}
public void addedFunctionB() {
System.out.println("为构件对象添加功能B");
}
}
装者模式的应用:
-mybatis 里的缓存: