Java Design Patterns Strategy Patterns

Introduction

Strategy Patterns define a list of algorithms and make them interchangeable.

The strategy pattern allows the algorithm vary independently from client to client.

We can select the behavior of an algorithm dynamically at runtime.

Use case

  • Based on the number of element we use different sorting algorithms.

Example

class JobManager {
   Job job;//  w w  w .jav  a2 s.  com

   public void setJob(Job ic) {
      job = ic;
   }

   public void showResult(String s1, String s2) {
      job.doJob(s1, s2);
   }
}

interface Job {
   void doJob(String s1, String s2);
}

class AddJob implements Job {
   public void doJob(String s1, String s2) {
      int int1, int2, sum;
      int1 = Integer.parseInt(s1);
      int2 = Integer.parseInt(s2);
      sum = int1 + int2;
      System.out.println(" The result of the addition is:" + sum);
   }
}

class AppendJob implements Job {
   public void doJob(String s1, String s2) {
      System.out.println(" The result of the addition is:" + s1 + s2);
   }
}

public class Main {
   public static void main(String[] args) {
      Job ic = null;
      JobManager cxt = new JobManager();
      String input1= "1", input2= "2";
  
      ic = new AddJob();
      cxt.setJob(ic);
      cxt.showResult(input1, input2);

      ic = new AppendJob();

      cxt.setJob(ic);
      cxt.showResult(input1, input2);
   }
}



PreviousNext

Related