意图
- Attach additional responsibilities to an object dynamically.
- 为一个对象动态的添加职责.
- Decorators provide a flexible alternative to subclassing for extending functionality.
- 对扩展功能来所,包装模式提供了一个比子类话更灵活的替代方式.
结构
- Component : defines the interface for objects that can have responsibilities added to them dynamically.
- Component : 为对象定义了一个接口使得可以动态的加载职责.
- Decorator : maintains a reference to a Component object and defines an interface that conforms to Component's interface.
- Decorator : 保有一个Component对象的引用并且定义了一个接口来执行Component中的接口方法.
- ConcreteDecorator : adds responsibilities to the component.
- ConcreteDecorator: 向component添加职责.
应用场景
- to add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
- 向单个对象动态和透明的添加职责,也就是说,不影响其他对象.
- for responsibilities that can be withdrawn.
- 对于可取消的职责.
- when extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing.
- 当通过子类化来扩展不现实时.有时需要大量单独的扩展并且为了支持每一种组合会使得子类膨胀.或者类可能被隐藏或者不能子类化.
作用效果
- More flexibility than static inheritance. The Decorator pattern provides a more flexible way to add responsibilities to objects than can be had with static (multiple) inheritance. With decorators responsibilities can be added and removed at run-time simply by attaching and detaching them.
- 比静态的继承更灵活.装饰模式提供了一种更灵活的方式来扩展对象的职责,相比于静态的(多个)子类.使用装饰器,职责可以在运行时添加或移除,只需装上货卸除他们.
- Avoids feature-laden classes high up in the hierarchy. Decorator offers a pay-as-you-go approach to adding responsibilities. Instead of trying to support all foreseeable features in a complex, customizable class, you can define a simple class and add functionality incrementally with Decorator objects. Functionality can be composed from simple pieces. As a result, an application needn't pay for features it doesn't use.
- 避免繁重的深层子类化.装饰器提供了按需的添加职责.避免试图在一个复杂的,客户化的子类中支持所有可预见的特性,你可以使用一个简单的类,然后增量式的装饰对象的功能.功能可以从一个个简单的部分组合.这样你的应用将不需要付出不使用的特性的代价.
- A decorator and its component aren't identical. A decorator acts as a transparent enclosure. But from an object identity point of view, a decorated component is not identical to the component itself. Hence you shouldn't rely on object identity when you use decorators.
- 一个装饰器和它的部件不是同一的.一个装饰器表现为一个透明的封装.但是用一个对象一致的角度,装饰的部件和部件本身是不一致的.因此当以使用包装器时应当不依赖于对象一致.
- Lots of little objects. A design that uses Decorator often results in systems composed of lots of little objects that all look alike. The objects differ only in the way they are interconnected, not in their class or in the value of their variables. Although these systems are easy to customize by those who understand them, they can be hard to learn and debug.
- 众多小对象.一个使用了装饰模式的设计导致一个有众多相似的小对象的系统.对象之间的区别仅仅在于他们之间的交互,而不在于他们的类或他们的值.虽然这里系统很容易被理解他们的人订制,但是他们很难学习和调试.