Strategy Pattern Example

๐ŸŽฏ Strategy Design Pattern in Java — Step-by-Step with Example

The Strategy Pattern is a behavioral design pattern that enables selecting an algorithm’s behavior at runtime.

It defines a family of algorithms, encapsulates each one, and makes them interchangeable.
This helps you avoid hardcoding logic and promotes flexibility and reusability.


๐Ÿง  Concept

  • Define a common strategy interface (for a family of related algorithms).

  • Create multiple concrete strategy classes, each implementing that interface.

  • Use a context class that maintains a reference to a strategy and delegates execution to it.

This lets you change an algorithm’s behavior dynamically at runtime without modifying existing code.


๐Ÿš— Real-World Analogy

Think of a navigation app (like Google Maps)
You can choose different travel strategies:

  • ๐Ÿš— Car route (fastest by road)

  • ๐Ÿš† Train route

  • ๐Ÿšถ Walking route

All these share the same interface: calculateRoute(),
but their internal logic differs.

You can switch the strategy anytime, depending on user preference or situation — that’s Strategy Pattern in action.


⚙️ Step-by-Step Implementation


๐Ÿงฉ Step 1: Define the Strategy Interface

package com.vinod.design.strategy; /** * Strategy interface defining a common operation. */ public interface PaymentStrategy { void pay(int amount); }

This interface represents the common behavior (payment operation) shared by all strategies.


๐Ÿงฉ Step 2: Create Concrete Strategies

Each class implements a different way to perform the payment.

package com.vinod.design.strategy; public class CreditCardPayment implements PaymentStrategy { @Override public void pay(int amount) { System.out.println("Paid " + amount + " using Credit Card."); } }
package com.vinod.design.strategy; public class PayPalPayment implements PaymentStrategy { @Override public void pay(int amount) { System.out.println("Paid " + amount + " using PayPal."); } }
package com.vinod.design.strategy; public class UpiPayment implements PaymentStrategy { @Override public void pay(int amount) { System.out.println("Paid " + amount + " using UPI."); } }

๐Ÿงฉ Step 3: Create the Context Class

The context uses a strategy object to execute the algorithm.
You can change the strategy dynamically by calling setPaymentStrategy().

package com.vinod.design.strategy; /** * Context class that uses a PaymentStrategy. */ public class PaymentContext { private PaymentStrategy paymentStrategy; // Constructor injection (optional) public PaymentContext(PaymentStrategy paymentStrategy) { this.paymentStrategy = paymentStrategy; } // Setter injection (allows dynamic strategy change) public void setPaymentStrategy(PaymentStrategy paymentStrategy) { this.paymentStrategy = paymentStrategy; } // Delegates behavior to the selected strategy public void executePayment(int amount) { if (paymentStrategy == null) { throw new IllegalStateException("Payment strategy not set!"); } paymentStrategy.pay(amount); } }

๐Ÿงฉ Step 4: Test the Strategy Pattern

package com.vinod.design.strategy; public class StrategyPatternTest { public static void main(String[] args) { // Pay using Credit Card PaymentContext context = new PaymentContext(new CreditCardPayment()); context.executePayment(500); // Change strategy at runtime to PayPal context.setPaymentStrategy(new PayPalPayment()); context.executePayment(1200); // Switch again to UPI context.setPaymentStrategy(new UpiPayment()); context.executePayment(250); } }

๐Ÿงพ Output

Paid 500 using Credit Card. Paid 1200 using PayPal. Paid 250 using UPI.

๐Ÿง  How It Works (Step-by-Step)

StepActionExplanation
1️⃣Client creates PaymentContextHolds a reference to a PaymentStrategy
2️⃣Client sets strategy (e.g., CreditCardPayment)Decides algorithm to use
3️⃣Context delegates callCalls strategy.pay(amount) internally
4️⃣Strategy executes its algorithmPerforms the desired operation
5️⃣Strategy can be switched dynamicallyClient can call setPaymentStrategy() anytime

๐Ÿงฉ UML-Like Text Diagram

+---------------------+ | PaymentStrategy | <--- Interface |---------------------| | + pay(amount):void | +---------+-----------+ | +-------------------+------------------+ | | | +----------------+ +----------------+ +----------------+ | CreditCardPayment | | PayPalPayment | | UpiPayment | |------------------| |----------------| |----------------| | + pay() | | + pay() | | + pay() | +------------------+ +----------------+ +----------------+ ^ | +----------------------+ | PaymentContext | |----------------------| | - strategy:PaymentStrategy | | + setPaymentStrategy() | | + executePayment() | +----------------------+

⚡ Benefits of Strategy Pattern

BenefitDescription
Open/Closed PrincipleYou can add new strategies without modifying existing code
Runtime FlexibilityChange algorithms dynamically
Code ReusabilityCommon logic stays in context; algorithms are modular
Clean DesignRemoves complex if-else or switch conditions
TestabilityEach strategy can be unit tested independently

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts