什么时候和如何应用策略模式而不是装饰模式? [英] When and How Strategy pattern can be applied instead of decorator pattern?

查看:145
本文介绍了什么时候和如何应用策略模式而不是装饰模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习设计模式,并尝试遵循Go4书。在第179页,在装饰图案一章中,有一行表示..通过将策略的数量从一个扩展到一个开放式列表,我们实现了与嵌套装饰器递归相同的效果。我不太明白这个说法。虽然策略侧重于具有独立的算法,可以动态设置,并且不了解他们所设置的客户端。而装饰器并不完全独立于他们装饰的客户端。实际上,它们与他们装饰的对象是一样的超类型。我在这里错过了一点吗?

解决方案

我将再多一点引用我认为需要的上下文有理由。


在组件类本质上是重量级的情况下,策略是一个更好的选择,从而使Decorator模式成本太高。在策略模式中,组件将其某些行为转发到单独的策略对象。策略模式允许我们通过替换策略对象来更改或扩展组件的功能。



例如,我们可以通过将组件延迟边框绘制来支持不同的边框样式一个单独的Border对象。 Border对象是一个封装了边框绘制策略的Strategy对象。通过将策略数量从一个扩展到一个开放式的列表,我们实现了与嵌套装饰器递归相同的效果。


全部这就是说,这两种模式都可以用来添加行为到基础组件,而使用Decorator添加多个行为,您可以嵌套装饰器,而在策略中,需要使用多种策略。



你是对的,策略通常比装饰器更独立于主要组件,但是他们可以知道组件。并且要使用策略模式,主要组件意识到存在策略,而Decorator不需要这样的策略。


I am learning design patterns and trying to follow Go4 book. On page:179, in the decorator pattern chapter, there is a line which says "..by extending the number of strategies from just one to an open-ended list, we achieve the same effect as nesting decorators recursively." I didn't quite get this statement. While strategies focuses on having independent algorithms, which can be set dynamically and don't know much about the client they are set in. Whereas decorators are not quite independent of the clients they decorate. In fact, they are of same supertype as the object they decorate. Am I missing a point here?

解决方案

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.

这篇关于什么时候和如何应用策略模式而不是装饰模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆