Where is the benefit in using the Strategy Pattern?

前端 未结 8 1099
太阳男子
太阳男子 2020-12-28 10:22

I\'ve looked at this explanation on Wikipedia, specifically the C++ sample, and fail to recognize the difference between just defining 3 classes, creating instances and call

8条回答
  •  别那么骄傲
    2020-12-28 10:34

    The strategy pattern allows you to exploit polimorphism without extending your main class. In essence, you are putting all variable parts in the strategy interface and implementations and the main class delegates to them. If your main object uses only one strategy, it's almost the same as having an abstract (pure virtual) method and different implementations in each subclass.

    The strategy approach offers some benefits:

    • you can change strategy at runtime - compare this to changing the class type at runtime, which is much more difficult, compiler specific and impossible for non-virtual methods
    • one main class can use more than one strategies which allows you to recombine them in multiple ways. Consider a class that walks a tree and evaluates a function based on each node and the current result. You can have a walking strategy (depth-first or breadth-first) and calculation strategy (some functor - i.e. 'count positive numbers' or 'sum'). If you do not use strategies, you will need to implement subclass for each combination of walking/calculation.
    • code is easier to maintain as modifying or understanding strategy does not require you to understand the whole main object

    The drawback is that in many cases, the strategy pattern is an overkill - the switch/case operator is there for a reason. Consider starting with simple control flow statements (switch/case or if) then only if necessary move to class hierarchy and if you have more than one dimensions of variability, extract strategies out of it. Function pointers fall somewhere in the middle of this continuum.

    Recommended reading:

    • http://www.industriallogic.com/xp/refactoring/
    • http://www.refactoring.com/

提交回复
热议问题