dimanche 27 juin 2021

Does strategy always needs to be passed from the client code in Strategy Pattern?

I have below piece of code:

public interface SearchAlgo { public Items search(); }

public class FirstSearchAlgo implements SearchAlgo { public Items search() {...} }

public class SecondSearchAlgo implements SearchAlgo { public Items search() {...} }

I also have a factory to create instances of above concrete classes based on client's input. Below SearchAlgoFactory code is just for the context.

public class SearchAlgoFactory {
   ...

   public SearchAlgo getSearchInstance(String arg) {
      if (arg == "First") return new FirstSearchAlgo();
      if (arg == "Second") return new SecondSearchAlgo();
   }

}

Now, I have a class that takes input from client, get the Algo from Factory and executes it.

public class Manager{
 
   public Items execute(String arg) {
      
        SearchAlgo algo = SearchAlgoFactory.getSearchInstance(arg);
        return algo.search();
   }

}

Question:

I feel that I am using both Factory and Strategy pattern but I am not sure 'cause whatever examples I have seen they all have a Context class to execute the strategy and client provides the strategy which they want to use. So, is this a correct implementation of Strategy?

Aucun commentaire:

Enregistrer un commentaire