NailYourInterview
Behavioural Design Patterns

Strategy Design Pattern in Java with Real Example

Master the Strategy Design Pattern in Java with real-life examples like payment methods and game behavior. Learn to switch algorithms at runtime easily.

Strategy Design Pattern

Video thumbnail

The Strategy Design Pattern is a behavioral pattern that helps you define a group of algorithms, keep each one in a separate class, and switch between them while the program is running.

Real-Life Examples

Payments

Strategy Design Pattern Example - Payments
Strategy Design Pattern Example - Payments

The image above shows a checkout page where a customer is entering their details to buy a product.

One important thing here is the payment method — how the user chooses to pay. We support multiple ways to pay, like Card, GPay, and PayPal.

Depending on the option selected by the user, a different pay() method is used.

  • If the user selects GPay, the pay() method will handle GPay payment.
  • If they select Card, then card payment logic will be used.

So basically, we are creating multiple versions of pay(), and using the correct one based on what the user picks.

Game Character

Strategy Design Pattern Example - Game
Strategy Design Pattern Example - Game

Imagine you're playing a game where the main character is a wizard. By default, the wizard throws fireballs.

The game has special power-ups that change how the wizard attacks:

  • If you take the fire power-up, the wizard throws fireballs.

  • If you take the lightning power-up, the wizard throws lightning.

  • If you take the ice power-up, the wizard freezes enemies.

So depending on what power-up the player takes, the attack() behavior changes during the game.

In both examples above, the behavior (pay() or attack()) is decided at runtime. That’s exactly what the Strategy Pattern helps with — switching behavior while the program is running without changing the code structure.

What Happens Without Strategy Pattern?

If we don’t use this pattern where it’s needed, we can run into a big problem called class explosion.

Let’s understand this with a simple example.

Suppose we have a Robot class. This robot can do three things:

  1. move() – how the robot moves

  2. speak() – how the robot communicates

  3. attack() – how the robot attacks

Each behavior has 3 different styles:

BehaviorStrategy Options
MoveWalk, Fly, Run
SpeakBeep, Speak, Silent
AttackPunch, Laser, Sword

If we use Strategy Pattern:

We create just 9 classes for each behavior:

  • Move Strategies: WalkStrategy, FlyStrategy, RunStrategy

  • Speak Strategies: BeepStrategy, SpeakStrategy, SilentStrategy

  • Attack Strategies: PunchStrategy, LaserStrategy, SwordStrategy

This means: If I want a robot that can Run, be Silent, and attack with a Laser, I simply inject the 3 strategies into the robot.

If I want a robot that can Walk, Speak, and Punch, I just plug in those strategies.

This gives us flexibility with only 9 strategy classes.

If we don’t use Strategy Pattern:

We have to create every possible combination of these behaviors in advance.

Total classes = move types × speak types × attack types = 3 × 3 × 3 = 27 robot classes!

RobotWalkBeepPunch;
RobotWalkBeepLaser;
RobotWalkBeepSword;
RobotWalkSpeakPunch;
RobotWalkSpeakLaser;
RobotWalkSpeakSword;
RobotWalkSilentPunch;
RobotWalkSilentLaser;
RobotWalkSilentSword;
 
RobotFlyBeepPunch;
RobotFlyBeepLaser;
RobotFlyBeepSword;
RobotFlySpeakPunch;
RobotFlySpeakLaser;
RobotFlySpeakSword;
RobotFlySilentPunch;
RobotFlySilentLaser;
RobotFlySilentSword;
 
RobotRunBeepPunch;
RobotRunBeepLaser;
RobotRunBeepSword;
RobotRunSpeakPunch;
RobotRunSpeakLaser;
RobotRunSpeakSword;
RobotRunSilentPunch;
RobotRunSilentLaser;
RobotRunSilentSword;

That's 27 classes just for 3 behaviors with 3 options each. Imagine what happens when we add more! This mess of too many classes is called Class Explosion, and it's a maintenance nightmare.

UML Diagram

UML for Strategy Design Pattern
UML for Strategy Design Pattern

This UML diagram shows how the pattern works:

  • IStrategy is the main interface.

  • Concrete strategies like CreditCardPayment, GPayPayment, PayPalPayment implement it.

  • The Context class holds a reference to a strategy and uses it to perform an action.

  • The client chooses and sets the strategy at runtime.

Code Example

Strategies

public interface PaymentStrategy {
    void pay(double amount);
}

Context

PaymentProcessor.java
public class PaymentProcessor {
    private PaymentStrategy strategy;
 
    public PaymentProcessor(PaymentStrategy strategy) {
        this.strategy = strategy;
    }
 
    public void setStrategy(PaymentStrategy strategy) {
        this.strategy = strategy;
    }
 
    public void processPayment(double amount) {
        strategy.pay(amount);
    }
}

Main Class (Client Code)

Main.java
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        double amount = 0;
        System.out.print("Enter payment amount: $");
        if (scanner.hasNextDouble()) {
            amount = scanner.nextDouble();
        }
        scanner.nextLine();
 
        System.out.println("Select payment method:");
        System.out.println("1. PayPal");
        System.out.println("2. GPay");
        System.out.println("3. Credit Card");
        System.out.print("Your choice: ");
        int choice = scanner.nextInt();
        scanner.nextLine();
 
        PaymentStrategy strategy = null;
 
        // We can use Factory Design Pattern for creating strategies
        switch (choice) {
            case 1:
                System.out.print("Enter your PayPal email: ");
                String email = scanner.nextLine();
                strategy = new PayPalPayment(email);
                break;
            case 2:
                System.out.print("Enter your pin: ");
                String pin = scanner.nextLine();
                strategy = new GooglePayPayment(pin);
                break;
            case 3:
                System.out.print("Enter your name: ");
                String name = scanner.nextLine();
                System.out.print("Enter your card number: ");
                String card = scanner.nextLine();
                System.out.print("Enter your CVV: ");
                String cvv = scanner.nextLine();
                System.out.print("Enter your expiry date (MM/YY): ");
                String expiry = scanner.nextLine();
                strategy = new CreditCardPayment(name, card, cvv, expiry);
                break;
            default:
                System.out.println("Invalid choice. Exiting.");
                return;
        }
 
        // Use context to process payment
        PaymentProcessor processor = new PaymentProcessor(strategy);
        processor.processPayment(amount);
 
        scanner.close();
    }
}

Key Benefits of the Strategy Design Pattern

On this page