Friday, 22 April 2016

Strategy Design Pattern

Strategy design pattern

If the algorithm for processing should change on demand, then use Strategy design pattern.
In a way it’s opposite to Template Design Pattern where the algorithm is fixed and the underlying implementation changes.
Algorithm is abstracted as a “Strategy” interface. All various algorithms must implement the Strategy interface.

There is a “Context” class that executes the algorithm. It takes the object of the algorithm to execute as well as any arguments that the algorithm may take.

public interface Strategy {

      boolean checkTemperature(int temperatureInF);

}

public class HikeStrategy implements Strategy {
      @Override
      public boolean checkTemperature(int temperatureInF) {
            if ((temperatureInF >= 50) && (temperatureInF <= 90)) {
                  return true;
            } else {
                  return false;
            }
      }

}

public class ColdStrategy implements Strategy {
      @Override
      public boolean checkTemperature(int temperatureInF) {
            if (temperatureInF <= 32) {
                  return true;
            } else {
                  return false;
            }
      }
}

public class Context {

      int temperatureInF;
      Strategy strategy;

      public Context(int temperatureInF, Strategy strategy) {
            this.temperatureInF = temperatureInF;
            this.strategy = strategy;
      }

      public void setStrategy(Strategy strategy) {
            this.strategy = strategy;
      }

      public int getTemperatureInF() {
            return temperatureInF;
      }

      public boolean getResult() {
            return strategy.checkTemperature(temperatureInF);
      }

}

public class MainClass {
      public static void main(String[] args) {
            int temperatureInF = 60;

            Strategy coldStrategy = new ColdStrategy();
            Context context = new Context(temperatureInF, coldStrategy);

            System.out.println("Is the required temperature (" + context.getTemperatureInF() + "F) . Keep in refrigerator? " + context.getResult());

            Strategy hikeStrategy = new HikeStrategy();
            context.setStrategy(hikeStrategy);

            System.out.println("Is the required temperature (" + context.getTemperatureInF() + "F) . Microwave? " + context.getResult());

      }

}


Code link : https://github.com/sksumit1/DesignPatterns

No comments:

Post a Comment