Java strategy design pattern

Dictionary meaning of strategy: A plan of action designed to achieve a long-term or overall aim.

Java strategy design pattern comes under behavioural design patterns. Strategy design pattern states that define multiple algorithms for a specific task and let the client application choose the algorithm to be used.

Collections.sort() method is one of the commonly used example of strategy design pattern. It takes Comparator as an argument and we can provide different implementations to Comparator interface. Now, Collections.sort() method will sort the objects based on the comparator implementation passed to it.

Example

Strategy.java

package com.w3schools;
 
public interface Strategy {
	public boolean strinComparision(String str1, String str2); 
}

StringComparisionByOperator.java

package com.w3schools;
 
public class StringComparisionByOperator implements Strategy {
	@Override
	public boolean strinComparision(String str1, String str2) {
		return str1 == str2;
	}	  	
}

StringComparisionByEquals.java

package com.w3schools;
 
public class StringComparisionByEquals implements Strategy {
	@Override
	public boolean strinComparision(String str1, String str2) {
		return str1.equals(str2);
	}	  	
}

StringComparisionByCompareTo.java

package com.w3schools;
 
public class StringComparisionByCompareTo implements Strategy {
	@Override
	public boolean strinComparision(String str1, String str2) {
		if(str1.compareTo(str2) == 0){
			return true;
		}else {
			return false;
		}
	}	  	
}

Context.java

package com.w3schools;
 
public class Context {
   private Strategy strategy;
 
   public Context(Strategy strategy){
      this.strategy = strategy;
   }
 
   public boolean executeStrategy(String str1, String str2){
      return strategy.strinComparision(str1, str2);
   }
}

StrategyPatternTest.java

package com.w3schools;
 
public class StrategyPatternTest {
  public static void main(String args[]){
      Context context = new Context(new StringComparisionByOperator());		
      System.out.println("String are equal: " + context.executeStrategy("w3schools", "w3schools"));
 
      context = new Context(new StringComparisionByOperator());		
      System.out.println("String are equal: " + context.executeStrategy("sahil", "vivek"));
 
      context = new Context(new StringComparisionByOperator());		
      System.out.println("String are equal: " + context.executeStrategy("sachin", "sachin"));
   }
}

Output

String are equal: true
String are equal: false
String are equal: true