一.介绍
装饰器模式(Decorator Pattern)属于结构型模式。在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能),不同装饰类之间可以灵活的排列组合
二.UML类图
三.具体代码
业务代码
public abstract class Decorator implements Component{
protected Component component;
public Decorator(Component component) {
this.component = component;
}
public abstract void operation();
}
class ConcreteDecorator1 extends Decorator{
public ConcreteDecorator1(Component component) {
super(component);
}
@Override
public void operation() {
addition();
component.operation();
}
public void addition(){
System.out.println("美颜效果");
}
}
class ConcreteDecorator2 extends Decorator{
public ConcreteDecorator2(Component component) {
super(component);
}
@Override
public void operation() {
addition();
component.operation();
}
public void addition(){
System.out.println("滤镜效果");
}
}
interface Component{
void operation();
}
class ConcreteComponent implements Component{
@Override
public void operation() {
System.out.println("基础的拍照功能");
}
}
客户端
public class Client {
public static void main(String[] args) {
Component component1 = new ConcreteDecorator1(new ConcreteComponent());
component1.operation();
Component component2 = new ConcreteDecorator2(new ConcreteDecorator1(new ConcreteComponent()));
component2.operation();
}
}
四.装饰器模式与代理模式对比
因为装饰器模式与代理模式的UML类图非常相似,所以来对比一下两者的区别 1.目的意图不同
2.使用时的差别
3.对于客户端来说
五.使用场景
六.在JDK中的应用
Java IO类库中有很多,例如
BufferedReader br = new BufferedReader(new FileReader("fileName.txt"));
br.read();
UML类图
七.在Spring中的应用
javax.servlet.ServletRequestWrapper
八.优点
|