> For the complete documentation index, see [llms.txt](https://jrp.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jrp.gitbook.io/notes/design-pattern/behavioural-strategy-pattern.md).

# Behavioural - Strategy Pattern

<figure><img src="/files/OrCYpAaiZtyhuEjCgWYd" alt=""><figcaption></figcaption></figure>

### Low Level Design

<figure><img src="/files/Fn2XPVbLc1a51XOL59An" alt=""><figcaption><p>strategy pattern</p></figcaption></figure>

{% hint style="info" %}
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 : &#x20;

If you refer State Pattern example,&#x20;

First behaviour : Take Coin,&#x20;

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.
{% endhint %}

| 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

```java
public interface PaymentStrategy {
	void pay();
}
```

#### Different Payment Strategies

```java
public class UPIStrategy implements PaymentStrategy {
	@Override
	public void pay() {
		System.out.println("UPI payment");
	}
}
```

```java
public class NetBankingStrategy implements PaymentStrategy {
	@Override
	public void pay() {
		System.out.println("Paying via internet banking");
	}
}
```

```java
public class CreditCardStrategy implements PaymentStrategy {
	@Override
	public void pay() {
		System.out.println("Paying via credit card);
	}
}
```

#### Context Class&#x20;

```java
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

```java
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&#x20;

* sorting strategies like Insertion Sort, Merge Sort etc.
* Allocation Strategies like Round-Robin Algorithm, Hashing Strategye etc.

Comparator Example = Strategy

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

If the client switches strategy:

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

Behavior changes **because the client selected a different strategy**.
