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

# Strategy Pattern

The **Strategy Pattern** is a Behavioral Design Pattern that allows you to define multiple algorithms (strategies) and switch between them dynamically at runtime without changing the main code.

It helps follow the **Open/Closed Principle**:

* Open for extension
* Closed for modification

***

## Real-Life Example

Think about a payment system:

A user can pay using:

* Credit Card
* PayPal
* Stripe
* Mobile Banking

Instead of writing large `if-else` conditions, we create separate payment strategies.

***

## Problem Without Strategy Pattern

```
class PaymentService {

    public function pay($method, $amount) {

        if($method == 'paypal') {
            return "Paid $amount using PayPal";
        }

        if($method == 'stripe') {
            return "Paid $amount using Stripe";
        }

        if($method == 'bkash') {
            return "Paid $amount using bKash";
        }
    }
}
```

### Problems

❌ Huge if-else blocks\
❌ Hard to maintain\
❌ Difficult to add new payment methods\
❌ Violates Open/Closed Principle

***

## Strategy Pattern Solution

### Step 1: Create Strategy Interface

```
interface PaymentStrategy
{
    public function pay($amount);
}
```

This interface defines a common behavior for all payment methods.

***

## Step 2: Create Concrete Strategies

### PayPal Strategy

```
class PaypalPayment implements PaymentStrategy
{
    public function pay($amount)
    {
        return "Paid {$amount} using PayPal";
    }
}
```

***

### Stripe Strategy

```
class StripePayment implements PaymentStrategy
{
    public function pay($amount)
    {
        return "Paid {$amount} using Stripe";
    }
}
```

***

### bKash Strategy

```
class BkashPayment implements PaymentStrategy
{
    public function pay($amount)
    {
        return "Paid {$amount} using bKash";
    }
}
```

***

## Step 3: Create Context Class

The Context class uses a strategy object.

```
class PaymentContext
{
    protected $paymentStrategy;

    public function __construct(PaymentStrategy $paymentStrategy)
    {
        $this->paymentStrategy = $paymentStrategy;
    }

    public function executePayment($amount)
    {
        return $this->paymentStrategy->pay($amount);
    }
}
```

***

## Step 4: Use Strategy Dynamically

### Pay with PayPal

```
$payment = new PaymentContext(
    new PaypalPayment()
);

echo $payment->executePayment(1000);
```

#### Output

```
Paid 1000 using PayPal
```

***

### Pay with Stripe

```
$payment = new PaymentContext(
    new StripePayment()
);

echo $payment->executePayment(2000);
```

***

### Pay with bKash

```
$payment = new PaymentContext(
    new BkashPayment()
);

echo $payment->executePayment(500);
```

***

## Full Working Example

```
<?php

interface PaymentStrategy
{
    public function pay($amount);
}

class PaypalPayment implements PaymentStrategy
{
    public function pay($amount)
    {
        return "Paid {$amount} using PayPal";
    }
}

class StripePayment implements PaymentStrategy
{
    public function pay($amount)
    {
        return "Paid {$amount} using Stripe";
    }
}

class BkashPayment implements PaymentStrategy
{
    public function pay($amount)
    {
        return "Paid {$amount} using bKash";
    }
}

class PaymentContext
{
    protected $paymentStrategy;

    public function __construct(PaymentStrategy $paymentStrategy)
    {
        $this->paymentStrategy = $paymentStrategy;
    }

    public function executePayment($amount)
    {
        return $this->paymentStrategy->pay($amount);
    }
}

$payment = new PaymentContext(
    new PaypalPayment()
);

echo $payment->executePayment(1000);
```

***

## UML Structure

```
        PaymentStrategy
              ▲
      -------------------
      |        |        |
 Paypal   Stripe   bKash

              ▲
       PaymentContext
```

***

## Advantages

### ✅ Easy to Add New Strategy

Add new payment methods without modifying existing code.

```
class NagadPayment implements PaymentStrategy
{
    public function pay($amount)
    {
        return "Paid {$amount} using Nagad";
    }
}
```

***

### ✅ Cleaner Code

Avoids huge conditional statements.

***

### ✅ Follows SOLID Principles

Especially:

* Open/Closed Principle
* Single Responsibility Principle

***

### ✅ Runtime Flexibility

Strategies can change dynamically.

```
$strategy = new StripePayment();

if($country == 'BD') {
    $strategy = new BkashPayment();
}
```

***

## Real Laravel Examples

| Feature               | Strategy Used       |
| --------------------- | ------------------- |
| Cache Drivers         | Redis/File/Database |
| Payment Gateways      | Stripe/PayPal       |
| Notification Channels | Mail/SMS/Slack      |
| Queue Drivers         | Redis/SQS/Database  |
| Authentication Guards | Session/API         |

***

## Another Example: Sorting Strategy

```
interface SortStrategy
{
    public function sort(array $data);
}

class BubbleSort implements SortStrategy
{
    public function sort(array $data)
    {
        sort($data);
        return $data;
    }
}

class ReverseSort implements SortStrategy
{
    public function sort(array $data)
    {
        rsort($data);
        return $data;
    }
}
```

***

## When to Use Strategy Pattern

Use Strategy Pattern when:

✅ Multiple algorithms exist\
✅ You want to switch behavior dynamically\
✅ Large if-else blocks exist\
✅ Logic changes frequently\
✅ Need clean and scalable architecture

***

## When NOT to Use

❌ Only one algorithm exists\
❌ Logic is very simple\
❌ Too many small classes become unnecessary

***

## Bridge Pattern vs Strategy Pattern

Both **Bridge** and **Strategy** patterns use composition instead of inheritance, so many developers confuse them.\
But their purposes are completely different.

***

## Main Difference

| Pattern          | Purpose                                   |
| ---------------- | ----------------------------------------- |
| Bridge Pattern   | Separates abstraction from implementation |
| Strategy Pattern | Changes behavior/algorithm dynamically    |

***

## Simple Understanding

### Bridge Pattern

Used when you have:

* Multiple abstractions
* Multiple implementations

And you want to avoid class explosion.

#### Focus:

👉 Structure and scalability

***

### Strategy Pattern

Used when you have:

* Multiple algorithms or behaviors

And you want to switch them dynamically.

#### Focus:

👉 Behavior selection

***

## Real-Life Analogy

### Bridge Pattern Example

Think of:

* Remote Controls
* TVs

Different remotes can work with different TVs.

```
Remote → Samsung TV
Remote → Sony TV
Advanced Remote → Samsung TV
Advanced Remote → Sony TV
```

Bridge separates:

* Abstraction = Remote
* Implementation = TV

***

### Strategy Pattern Example

Think of payment methods:

* PayPal
* Stripe
* bKash

You choose one strategy dynamically.

```
Checkout → PayPal
Checkout → Stripe
Checkout → bKash
```

***

## 1. Strategy Pattern Example

### Goal

Change payment behavior dynamically.

***

### Strategy Interface

```
interface PaymentStrategy
{
    public function pay($amount);
}
```

***

### Concrete Strategies

```
class PaypalPayment implements PaymentStrategy
{
    public function pay($amount)
    {
        return "Paid via PayPal";
    }
}

class StripePayment implements PaymentStrategy
{
    public function pay($amount)
    {
        return "Paid via Stripe";
    }
}
```

***

### Context Class

```
class PaymentContext
{
    protected $strategy;

    public function __construct(PaymentStrategy $strategy)
    {
        $this->strategy = $strategy;
    }

    public function execute($amount)
    {
        return $this->strategy->pay($amount);
    }
}
```

***

### Usage

```
$payment = new PaymentContext(
    new PaypalPayment()
);

echo $payment->execute(1000);
```

***

## Strategy Pattern Structure

```
Context → Strategy Interface → Concrete Strategies
```

***

## Strategy Pattern Purpose

✅ Swap algorithms\
✅ Dynamic behavior\
✅ Remove if-else conditions\
✅ Encapsulate business rules

***

## 2. Bridge Pattern Example

### Goal

Separate abstraction from implementation.

***

## Problem Without Bridge

```
SamsungBasicRemote
SamsungAdvancedRemote
SonyBasicRemote
SonyAdvancedRemote
LGAdvancedRemote
...
```

Huge class explosion.

***

## Bridge Solution

***

### Implementation Interface

```
interface TV
{
    public function on();
    public function off();
}
```

***

### Concrete Implementations

```
class SamsungTV implements TV
{
    public function on()
    {
        return "Samsung TV ON";
    }

    public function off()
    {
        return "Samsung TV OFF";
    }
}
```

***

```
class SonyTV implements TV
{
    public function on()
    {
        return "Sony TV ON";
    }

    public function off()
    {
        return "Sony TV OFF";
    }
}
```

***

## Abstraction Class

```
class RemoteControl
{
    protected $tv;

    public function __construct(TV $tv)
    {
        $this->tv = $tv;
    }

    public function turnOn()
    {
        return $this->tv->on();
    }
}
```

***

## Refined Abstraction

```
class AdvancedRemote extends RemoteControl
{
    public function mute()
    {
        return "TV Muted";
    }
}
```

***

## Usage

```
$remote = new AdvancedRemote(
    new SamsungTV()
);

echo $remote->turnOn();
```

***

## Bridge Pattern Structure

```
Abstraction → Implementation Interface → Concrete Implementations
```

***

## Bridge Pattern Purpose

✅ Avoid class explosion\
✅ Independent scalability\
✅ Separate abstraction from implementation\
✅ Better flexibility

***

## Key Differences

| Feature              | Strategy                | Bridge                                |
| -------------------- | ----------------------- | ------------------------------------- |
| Type                 | Behavioral Pattern      | Structural Pattern                    |
| Purpose              | Change behavior         | Separate abstraction & implementation |
| Focus                | Algorithms              | Structure                             |
| Runtime Change       | Yes                     | Usually not primary goal              |
| Composition Used For | Behavior                | Architecture                          |
| Main Problem Solved  | Large conditional logic | Class explosion                       |
| Example              | Payment methods         | Remote + TV                           |

***

## Easy Interview Answer

### Strategy Pattern

> Strategy Pattern changes object behavior dynamically by selecting different algorithms at runtime.

***

### Bridge Pattern

> Bridge Pattern separates abstraction from implementation so both can evolve independently.
