装饰模式(Decorator Pattern)
定义:Attach additional responsibilities to an object dynamically keeping
the same interface.Decorators provide a flexible alternative to
subclassing for extending
functionality.(动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。)
装饰模式的组成:
- 抽象构件角色(Component):定义一个抽象接口,以规范准备接收附加责任的对象。
- 具体构件角色(Concrete Component):这是被装饰者,定义一个将要被装饰增加功能的类。
- 装饰角色(Decorator):持有一个构件对象的实例,并定义了抽象构件定义的接口。
- 具体装饰角色(Concrete Decorator):负责给构件添加增加的功能。
使用场景:
- 需要扩展一个类的功能,或给一个类增加附加功