9

我正在学习设计模式并尝试遵循 Go4 书。在第 179 页,在装饰器模式章节中,有一行说

“..通过将策略的数量从一个扩展到一个开放式列表,我们可以实现与递归嵌套装饰器相同的效果。”

我不太明白这个说法。

策略专注于拥有独立的算法,这些算法可以动态设置,并且不太了解它们所在的客户端。

而装饰者并不完全独立于他们所装饰的客户。事实上,它们与它们装饰的对象具有相同的超类型。

我在这里错过了一点吗?

4

5 回答 5

15

I'll quote a little more of the context that I think is needed for this to make sense.

Strategies are a better choice in situations where the Component class is intrinsically heavyweight, thereby making the Decorator pattern too costly to apply. In the Strategy pattern, the component forwards some of its behavior to a separate strategy object. The Strategy pattern lets us alter or extend the component's functionality by replacing the strategy object.

For example, we can support different border styles by having the component defer border-drawing to a separate Border object. The Border object is a Strategy object that encapsulates a border-drawing strategy. By extending the number of strategies from just one to an open-ended list, we achieve the same effect as nesting decorators recursively.

All this is saying is that both patterns can be used to add behavior to your base component, and that with Decorator, to add multiple behaviors, you can nest the decorators, while with Strategy, you need to use multiple strategies.

You're right that strategies are generally more independent of the main component than decorators, but it is possible for them to be aware of the component. And to use the Strategy pattern, the main component is aware of the existence of strategies, where that's not needed with Decorator.

于 2010-12-04T17:42:58.803 回答
6

要使用他们的示例,您可能有一个可以滚动的窗口类和/或以各种方式绘制其边框(或根本不绘制)。如果您要使用继承来涵盖所有这些功能,那么您需要一个子类来处理每种可行的功能组合(无边框无滚动、无边框无滚动、无边框滚动、边框和滚动等)​​。当您添加更多功能时,这是一个不灵活的维护噩梦,因为类的数量呈爆炸式增长。

他们在这里提出的主要观点是,您可以使用策略模式或装饰器模式来更好地解决这个问题。您可以有一个封装滚动策略对象和边框策略对象的 Window 类。或者,您可以获取 Window 对象,将其包装在边框装饰器中,然后将其包装在滚动装饰器中。

但是您的理解完全正确;这是两种不同的设计模式,具有不同的特性,导致不同的应用。使用装饰器,组件不知道正在添加功能的代理......因此您最终倾向于围绕现有的组件类进行构建。对于策略,情况正好相反,因为组件正在使用(因此知道)代理来执行各种任务——这些代理通常不知道它们的管理组件。

于 2010-12-04T17:30:48.380 回答
1

当您想对某事使用多种方法时,请使用策略模式。当您想创建某些东西可能会或可能不会用于更改对象/组件/任何东西的东西时,那么您应该使用装饰器。换句话说,也可以说装饰器可能会添加功能(装饰)对象,而策略可能会交换功能。

于 2013-06-11T13:15:52.430 回答
0

The distinction is that in Strategy pattern, one Strategy object can be used to provide information to the Context at one time. With Decorator, you can stack Strategies on top of each other, and thus have what they refer to as "open-ended" numbers.

于 2010-12-04T17:37:22.853 回答
0

当对象的身份对您很重要时,可以应用策略模式。无论应用了多少策略,对象标识仍然存在,但对于装饰器模式,对象被封装在彼此内部,原始标识将在转换中丢失

  • 装饰图案改变对象的皮肤

  • 策略模式改变了对象的内涵。

于 2013-04-17T11:19:43.007 回答