装饰器模式(Decorator Pattern)也称为包装模式(Wrapper Pattern),是 GoF 的 23 种设计模式中的一种结构型设计模式。装饰器模式 是指在不改变原有对象的基础之上,将功能附加到对象上,提供了比继承更有弹性的替代方案(扩展原有对象的功能)。
装饰器模式 的核心是功能扩展,使用装饰器模式可以透明且动态地扩展类的功能
~
本篇内容包括:关于装饰器模式、装饰器实现 Demo
装饰器模式(Decorator Pattern)也称为包装模式(Wrapper Pattern),是 GoF 的 23 种设计模式中的一种结构型设计模式。
装饰器模式 是指在不改变原有对象的基础之上,将功能附加到对象上,提供了比继承更有弹性的替代方案(扩展原有对象的功能)。
装饰器模式 的核心是功能扩展,使用装饰器模式可以透明且动态地扩展类的功能
适配器模式一般包含四种角色:
# 装饰器模式的优点
# 装饰器模式的缺点
装饰方式可能比较复杂,如果嵌套太多,容易造成代码可读性变差和出错。
对装饰器模式来说,装饰者(decorator)和被装饰者(decoratee)都实现同一个接口。对代理模式来说,代理类(proxy class)和真实处理的类(real class)都实现同一个接口,他们之间的边界确实比较模糊,两者都是对类的方法进行扩展,具体区别如下:
# Component 抽象构件角色
interface Component {public void operation();
}
# ConcreteComponent 具体构件角色
class ConcreteComponent implements Component {public ConcreteComponent() {System.out.println("创建具体构件角色");}public void operation() {System.out.println("调用具体构件角色的方法operation()");}
}
# Decorator 抽象装饰角色
abstract class Decorator implements Component {private Component component;public Decorator(Component component) {this.component = component;}public void operation() {component.operation();}
}
# ConcreteDecorator 具体装饰角色
class ConcreteDecorator extends Decorator {public ConcreteDecorator(Component component) {super(component);}public void operation() {super.operation();addedFunction();}public void addedFunction() {System.out.println("为具体构件角色增加额外的功能addedFunction()");}
}
public class Client {public static void main(String[] args) {Component p = new ConcreteComponent();p.operation();Component d = new ConcreteDecorator(p);d.operation();}
}