关于Strategy和State设计模式
Posted 月落无影
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于Strategy和State设计模式相关的知识,希望对你有一定的参考价值。
之前,我在描述我所采用的设计模式时,一直在Strategy和State之间犹豫,略微有些拿捏不准,说哪种设计模式好。结果到最后,会根据自己所想,觉得是State就是State,觉得Strategy就是Strategy,不过,说的时候,还是会带有些犹豫。最近看Martin Fowler的《重构,改善既有代码的设计》一书,上面说到:
At this stage the choice of pattern (and name) reflects how you want to think about the structure. At the moment I‘m thinking about this as a state of movie(当前模块是描述movie的一个模块). If I later decide a strategy communicates my intention better, I will refactor to do this by changing the names.
该书在Replace Type Code with State/Strategy上写道:
State and strategy are very similar, so the refactoring is the same whichever you use, and it doesn‘t really matter. Choose the pattern that better fits the specific circumstances. If you are trying to simplify a single algorithm with Replace Conditional with Polymorphism, strategy is the better term. If you are going to move state-specific data and you think of the object as changing state, use the state pattern.
所以,在我看来,对于使用State或者Strategy来说,没有必要纠结。你可以认为你使用的State或者Strategy,只要你可以熟练使用。在交流的时候,知道State或者Strategy基本是等价的,所以不要太在意别人怎么说。对外,你可以说你使用了State设计模式,或者Strategy设计模式,或者State/Strategy设计模式就可以了。
以上是关于关于Strategy和State设计模式的主要内容,如果未能解决你的问题,请参考以下文章