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

问题描述

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

解决方案

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

全部这就是说,这两种模式都可以用来添加行为到基础组件,而使用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.

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.

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

09-23 00:16