概述
The decorator pattern provides a flexible alternative to subclassing for extending functionality. When using subclassing, different subclasses extend a class in different ways. However, an extension is bound to the class at compile-time and can't be changed at run-time. The decorator pattern allows responsibilities to be added (and removed from) an object dynamically at run-time. It is achieved by defining Decorator objects that
- implement the interface of the extended (decorated) object (Component) transparently by forwarding all requests to it.
- perform additional functionality before or after forwarding a request.
This allows working with different Decorator objects to extend the functionality of an object dynamically at run-time.
针对于功能扩展需求场景,装饰器模式提供一个不用子类化(继承)的灵活的替代方案。当你使用子类化(继承)方案时,子类以不同的方式继承一个类。但是扩展的功能在编译时被绑定到类上并且在运行时不能更改。