Search code examples
design-patternsrefactoringstrategy-pattern

Alternative Pattern to Strategy


I have a piece of code where I started to put the strategy pattern in place, say as follows:

IStrategy
StrategyA : IStrategy
StrategyB : IStrategy
StrategyC : IStrategy

The interface just has a Calculate method on it. After implementing, it turned out that all 3 concrete types had identical code for the Calculate method and two identically named Properties, just with different values set.

So to remove duplication I made the interface an abstract class and moved the method and properties down to that, just setting the base properties with their respective values from within construction of the concrete types.

Now I know patterns aren't hard and fast rules, merely guidelines, but I've warped this so far from the guidelines that I can't help but think there's another pattern I should be looking at?

Can anyone suggest any other approaches please, that leave me so it would be easy to add on new 'Strategies' down the line. It may turn out that we need to alter the logic in some of these new cases, so how could I structure that so I don't have repeating code, but have a flexible design that lets me alter things down the line?

Thanks.


Solution

  • Other alternative you can use is Template pattern. But it has problem: it does allow you to change the algorithm for the new cases but in a very limited way.

    So if flexibility is your aim, Strategy is still the best answer and you are correctly right to create an abstract class for the common case.