[TOC]
装饰器模式
动态的给一个对象添加一些额外的职责。就增加功能来说,装饰器模式比生成子类更灵活。
在装饰模式中, 必然有一个最基本、 最核心、 最原始的接口或抽象类充当 Component抽象构件。
优点
- 装饰类和被装饰类可以独立发展,不会互相耦合。
- 装饰器模式是继承关系的替代方案
- 装饰器模式可以动态的扩展一个实现类的功能。
缺点
多层装饰比较复杂。尽量减少装饰类数量,以便降低系统复杂度。
代码
定义一个接口或者一个抽象类,装饰器中最基本最核心对象。
1 | public interface Component { |
定义具体构件,Component的实现,被装饰类
1 | public class ConcreteComponent implements Component { |
定义装饰角色,实现接口或抽象方法,属性里有一个private变量指向Component抽象构件。
1 | public abstract class Decorator implements Component{ |
Decorator类并不是必须的。
具体的装饰类:
1 | public class ConcreteDecorator1 extends Decorator { |
main方法测试
1 | public static void main(String[] args){ |
测试结果:
1 | 原来的方法 |
装饰器模式使用场景
- 需要扩展一个类的功能,或给一个类增加附加功能;
- 动态的给一个对象增加附加功能,这些功能可以再动态的撤销;
- 为一批兄弟类进行改装或增加功能。