The Open-Closed Principle
Classed should be open for extension,but closed for modification.
The Decorator Pattern attaches additional responsibilities to an object dynamically.Decroators provide a flexible alternative to subclassing for extending functionality.
Decorator Pattern其实就是利用组合动态扩展功能,而不是使用继承。拿本文的例子来讲,饮料是一个抽象类,具体的被装饰者和装饰者都要继承这个抽象类,具体的讲,比如一种咖啡,它需要添加糖啊,奶啊,也可能会添加别的东西,还可能已经加完糖和奶了,再加一点糖,这样,咖啡继承自饮料,是需要被装饰的饮料,糖和奶则需要继承自具体的装饰者,而具体的装饰者则继承自饮料,在具体的装饰者中使用组合,便于在该装饰者中设置被装饰的对象,这样,即使咖啡需要加盐,只需要添加一个具体的装饰者类就可以实现,也和符合开闭原则。算帐时,也就实现了根据所加的调料动态计算。
Inheritance is one form of extension, but not necessarily the best way to achieve flexibility
in our designs.
In our designs we should allow behavior to be extended without the need to modify existing code.
Composition and delegation can often be used to add new behaviors at runtime.
The Decorator Pattern provides an alternative to subclassing for extending behavior.
The Decorator Pattern involves a set of decorator classes that are used to wrap concrete components.
Decorator classes mirror the type of the components they decorate. (In fact, they are the same type as the components they decorate, either through inheritance or interface implementation.)
Decorators change the behavior of their components by adding new functionality before and/or after (or even in place of) method calls to the component.
You can wrap a component with any number of decorators.
Decorators are typically transparent to the client of the component; that is, unless the client is relying on the
component’s concrete type.
Decorators can result in many small objects in our design, and overuse can be complex.