CodesJava

Easy learning with example program codes

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.codesjava;
 
public interface Strategy {
	public boolean strinComparision(String str1, String str2); 
}

StringComparisionByOperator.java

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

StringComparisionByEquals.java

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

StringComparisionByCompareTo.java

package com.codesjava;
 
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.codesjava;
 
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.codesjava;
 
public class StrategyPatternTest {
  public static void main(String args[]){
      Context context = new Context(new StringComparisionByOperator());		
      System.out.println("String are equal: " + context.executeStrategy("codesjava", "codesjava"));
 
      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
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki