jeudi 12 janvier 2017

Is it good idea to combine Strategy pattern, Factory pattern, and Chain of Responsibility pattern to avoid if/swich statements?

Is it good idea to combine Strategy pattern, Factory pattern, and Chain of Responsibility pattern to avoid if/swich statements?

In normal situation, strategy context must to contains if or else statements to choose which strategy use. For example:

public class StrategyContext {
   @Autowired
   private Strategy defaultSt;
   @Autowired
   private Strategy otherSt;

   public void process(String strategy) {
       if(strategy.equals("A"))
            defaultSt.doSomething();
       else if(strategy.equals("B")}
            ethoerSt.doSomething();
       ......
       ......
   }
}  

Of course in practices a if with strategy choose logic are more complicated than only equals.
I think it is not good solution becouse:

Firstly: In this case context change strategy itself and I think in strategy context should get concrete strategy from outside.

Secondly: if/switch! Every time when new strategy will be created, at StrategyContext we have to add another if statement. I am not a specialist ;) but probably it is breaking the rule of Open/Closed Principle.

I have a idea to extract if statements to chain of responsibility pattern. Each chain element check if object pass as argument to chain, have to be handle be its strategy and return it or invoke another chain element.

So, what do you thnik about it?

Aucun commentaire:

Enregistrer un commentaire