Search code examples
oopdesign-patternsstrategy-patternopen-closed-principle

Strategy Pattern and Open-Closed Principle Conflict


I was reading through strategy pattern and was trying to implement it but I have got stuck at deciding the strategy implementation which I feel violates the open-closed principle.

In strategy pattern we code to interface and based on client interaction we will pass in the strategy implementation.

Now if we have bunch of strategies so we need to decide using conditions which strategy the client chooses something like

IStrategy str;
    if(stragety1) {
     str = new Strategy1()
    } else if (stragety2) {
     str = new Strategy2()
    } and so on..
str.run()

Now as per open-closed principle the above is open to extension but it is not closed to modification

If I need to add another strategy(extension) in future I do need to alter this code.

is there a way where this could be avoided or it is how we need to implement strategy pattern ?


Solution

  • This is indeed not closed to modification, but that is due to the way you initialize. You are using a value (enum?) to determine which Strategy subclass should be used. As @bpjoshi points out their comment, this is more of a Factory pattern.

    Wikipedia discusses how a Strategy pattern can support the Open/Closed Principle, instead of hampering it.
    In that example, they use a Car class with a Brake Strategy. Some cars brake with ABS, some don't. Different Car subclasses and instances can be given different Strategies for braking.

    To get your code closed for modification, you need to select the Strategies differently. You want to select the Strategy in the place where new behavior or subclass is defined. You'd have to refactor your code so that the specific Strategy subclass is applied at the point where the code is extended.