Strategy Design Pattern

The strategy design pattern allows you to create Context classes, which use Strategy implementation classes for applying business rules.
Use Strategy design pattern when you need to define family of algorithms, encapsulate each one and make them interchangeable.
Use strategy design pattern when you need to use one of several algorithms dynamically.

Strategy Design Pattern

Benefits

  • Reduces multiple if-else statements at client side.
  • Hides complex, algorithmic-specific data from client.

Example of Strategy Design Pattern in Java Library

One good example of a Strategy pattern from JDK itself is a Collections.sort() method and the Comparator interface, which is a strategy interface and defines a strategy for comparing objects. Because of this pattern, we don’t need to modify the sort() method (closed for modification) to compare any object; at the same time, we can implement a Comparator interface to define a new comparing strategy (open for extension).

This pattern is actually based upon the Open-Closed design principle and if you understand that principle then its quite easy for you to understand the Strategy pattern as well.

Example
Strategy Design Pattern Example

 
interface IPaymentStrategy {

	public void pay(int billAmount);

}
public class DebitCardStrategy implements IPaymentStrategy {

	public void pay(int billAmount) {
		System.out.println("Charging " + billAmount + " using Debit Card...");
		System.out.println("Thank you!!");
	}
}
public class ChequeStrategy implements IPaymentStrategy {

	public void pay(int billAmount) {
		System.out.println("Charging " + billAmount + " using Check...");
		System.out.println("Thank you!!");
	}
}
public class CashStrategy implements IPaymentStrategy {
	
	public void pay(int billAmount) {
		System.out.println("Charged " + billAmount + " using Cash...");
		System.out.println("Thank you!!");
	}
}
public class Customer {
	private IPaymentStrategy paymentStrategy;

	public Customer(IPaymentStrategy paymentStrategy) {
		this.paymentStrategy = paymentStrategy;
	}

	public void pay(int billAmount) {
		paymentStrategy.pay(billAmount);
	}
}
public class TestClass {
	public static void main(String[] args) {
		Customer customer1 = new Customer(new DebitCardStrategy());
		customer1.pay(1000);

		Customer customer2 = new Customer(new CashStrategy());
		customer2.pay(5000);
	}
}

Author: Mahesh

Technical Lead with 10 plus years of experience in developing web applications using Java/J2EE and web technologies. Strong in design and integration problem solving skills. Ability to learn, unlearn and relearn with strong written and verbal communications.