關於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設計模式