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.

本文介绍了开闭原则和装饰器模式。装饰器模式利用组合动态扩展对象功能,而非继承。以咖啡添加调料为例,说明该模式符合开闭原则,能根据所加调料动态计算。同时指出继承并非实现灵活性的最佳方式,装饰器模式可替代子类化扩展行为,但可能产生大量小对象,过度使用会变复杂。
1101

被折叠的 条评论
为什么被折叠?



