mercredi 29 novembre 2017

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 ?

Aucun commentaire:

Enregistrer un commentaire