1.简介
装饰模式(Decorator Pattern)其定义如下:
Attach additionalresponsibilities to an object dynamically keeping the same interface.Decorators provide aflexible alternative to subclassing for extending functionality.
动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。
2.类图
3.角色
角色 | 功能 | 样例 |
---|---|---|
Component | 一般是一个接口 | ServletRequest |
ConcreteComponent | 最核心、最原始、最基本的接口或抽象类的实现, 你要装饰的就是它 |
org.apache.catalina.connector.Request tomcat基础实现 |
Decorator | 一般是一个抽象类,实现接口或者抽象方法 有一个private变量指向Component抽象构件 原有功能委托给依赖的Component完成
扫描二维码关注公众号,回复:
9814227 查看本文章
新增功能在原有逻辑包一层 |
ServletRequestWrapper |
ConcreteDecorator | 具体的装饰类 | HttpServletRequestWrapper |
4.应用场景
- 需要扩展一个类的功能,或给一个类增加附加功能。
- 需要动态地给一个对象增加功能,这些功能可以再动态地撤销。
- 需要为一批的兄弟类进行改装或加装功能,当然是首选装饰模式。
本文的样例就是ServletRequest,最基础的实现是org.apache.catalina.connector.Request,主要封装了通信层面的字段,
它的装饰者类是org.apache.catalina.connector.RequestFacade,主要在Request的实现方法外包了一层权限控制,
其中一个方法如下:
@Override
public Enumeration<String> getParameterNames() {
if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
if (Globals.IS_SECURITY_ENABLED){
return AccessController.doPrivileged(
new GetParameterNamesPrivilegedAction());
} else {
return request.getParameterNames();
}
}
5.优缺点
要点 | 解释 | |
---|---|---|
优点 | 装饰类和被装饰类可以独立发展, 而不会相互耦合 |
Component类无须知道Decorator类, Decorator类是从外部来扩展Component类的功能, 而Decorator也不用知道具体的构件。 |
装饰模式是继承关系的一个替代方案 | 不管装饰多少层,返回的对象还是Component,实现的还是is-a的关系。 装饰模式可以动态地扩展一个实现类的功能。 |
|
缺点 | 复杂 | 可读性差 |