Behavioural - Strategy Pattern

It helps to define multiple Strategies for the same task and user can select any strategy

Low Level Design

strategy pattern

This looks similar to State Pattern, then what is the difference between State Pattern and Strategy Pattern?

The difference lies in intention. In the State Pattern, the behaviour the object gets changed multiple times when the state of the object gets changed by the context holder.

For example :

If you refer State Pattern example,

First behaviour : Take Coin,

Second behaviour : Release Product (Vending machine controls it)

But in Strategy Pattern, you have to choose which Strategy to select. (You are the controller)

For Example : You need to select one payment method to pay for the products present in your cart. You choose.

Strategy Pattern
State Pattern

Client chooses which algorithm (strategy) to use.

Object chooses its next state based on internal rules.

Focus: interchangeable algorithms.

Focus: behavior changes over time based on state transitions.

The object’s behavior doesn’t change by itself; caller sets the strategy.

The object’s behavior changes automatically when its internal state changes.

Client controls switching.

Context controls switching.

Implementation

Interface

public interface PaymentStrategy {
	void pay();
}

Different Payment Strategies

public class UPIStrategy implements PaymentStrategy {
	@Override
	public void pay() {
		System.out.println("UPI payment");
	}
}
public class NetBankingStrategy implements PaymentStrategy {
	@Override
	public void pay() {
		System.out.println("Paying via internet banking");
	}
}
public class CreditCardStrategy implements PaymentStrategy {
	@Override
	public void pay() {
		System.out.println("Paying via credit card);
	}
}

Context Class

public class ShoppingCart { // Can be Abstract class in case of various shoping cart (mobile/web)
	PaymentStrategy paymentStrategy;

	ShoppingCart(PaymentStrategy paymentStrategy) {
		this.paymentStrategy = paymentStrategy;
	}

	void makePayment() {
		paymentStrategy.pay();
	}
}

Customer

public class Customer {

	public static void main(String[] args) {
		ShoppingCart cart = new ShoppingCart(new CreditCardStrategy());
		cart.makePayment();
		
		//Another order
		ShoppingCart cart = new ShoppingCart(new NetBankingStrategy());
		cart.makePayment();
	}
}

Some other examples

  • sorting strategies like Insertion Sort, Merge Sort etc.

  • Allocation Strategies like Round-Robin Algorithm, Hashing Strategye etc.

Comparator Example = Strategy

Collections.sort(list, Comparator.reverseOrder()); // Client decides strategy

If the client switches strategy:

Collections.sort(list, Comparator.naturalOrder()); // Client changes behavior

Behavior changes because the client selected a different strategy.

Last updated

Was this helpful?