在oo中,一般有2中方式可以实现给一个类或对象增加行为:
1.继承机制
使用继承机制给现有类增加 功能,这种方法是静态的,用户 不能控制增加行为的方式和时机
2.关联机制
关联机制是一种更加灵活的方法,即将一个类的对象嵌入到另一个对象中,由另一个对象来决定是否调用嵌入对象的行为并扩展自己的行为,我们称这个对象为装饰器(decorator)。为了使得装饰器与他所装饰的对象对客户端来说透明,装饰器类和被装饰的类必须实现相同的接口,客户端使用时无需关心一个类的对象是否被装饰过,可以一致性第使用未被装饰的对象以及装饰好的对象。
装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任,换言之,客户端并不会觉得对象在装饰前后有什么不同。
定义:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
The classes and/or objects participating in this pattern are:
-
Component (LibraryItem)
- defines the interface for objects that can have responsibilities added to them dynamically.
-
ConcreteComponent (Book, Video)
- defines an object to which additional responsibilities can be attached.
-
Decorator (Decorator)
- maintains a reference to a Component object and defines an interface that conforms to Component's interface.
-
ConcreteDecorator (Borrowable)
- adds responsibilities to the component.