design-patterns - 何时以及如何应用策略模式代替装饰器模式?

标签 design-patterns strategy-pattern

我正在学习设计模式,并试图遵循Go4书。在页面上:179,在装饰器模式一章中,有一行显示

"..by extending the number of strategies from just one to an open-ended list, we achieve the same effect as nesting decorators recursively."



我不太明白这句话。

策略着重于拥有独立的算法,这些算法可以动态设置,并且对所设置的客户端不甚了解。

装饰者并不是完全独立于他们装饰的客户。实际上,它们与装饰的对象具有相同的父类(super class)型。

我在这里想漏点吗?

最佳答案

我将引用更多我认为需要的上下文才能使之有意义。

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.


这说明这两种模式都可以用于向基本组件添加行为,而Decorator可以用于添加多种行为,可以嵌套装饰器,而Strategy则需要使用多种策略。
没错,策略通常比装饰器更独立于主要组件,但他们可能会意识到组件。要使用策略模式,主要组件要知道策略的存在,而Decorator则不需要。

关于design-patterns - 何时以及如何应用策略模式代替装饰器模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4354611/

相关文章:

c# - 策略工厂模式的 autofac 配置(已经解决)

java - 我是否必须在主类中编写每个方法才能使用它(策略模式)?

c++ - 自动代理类

java - 什么是 Java EE 负载提取器模式?

cakephp - MVC : Correct pattern to reference objects from a different model

ruby-on-rails - 策略模式文件位置 Rails

c# - 实现策略模式。我每次都必须 'new up' 吗?

java - 根据Java中对象的类型选择实现

java - 多线程环境下的单例模式

HTML5 法国车牌号输入模式