π What is the Strategy Pattern?
The Strategy Pattern is a behavioral design pattern that enables selecting an algorithm at runtime β encapsulating different strategies (algorithms) and making them interchangeable.
β When Should You Use It?
- When you need multiple variations of an algorithm.
- When you want to decouple the behavior from the context class.
- When you want to follow the Open-Closed Principle β extend behavior without modifying existing code.
π§ Real-World Analogy
Think of a navigation app π like Google Maps. Based on your need, you can choose:
- Drive
- Walk
- Cycle
- Public Transit
Each of these is a strategy to reach the same goal: your destination.
π§± Structure
+------------------+ +-----------------------+
| Context |<------->| Strategy |
+------------------+ +-----------------------+
| - strategy: S | | +execute(): void |
| +setStrategy(S) | +-----------------------+
| +executeStrategy()| / | \
+------------------+ ConcreteStrategyA ConcreteStrategyB ...
π§ Example: Payment System with Strategy Pattern
Weβll create a PaymentStrategy interface with multiple payment types.
β 1. Strategy Interface
public interface PaymentStrategy {
void pay(int amount);
}
β 2. Concrete Strategies
public class CreditCardPayment implements PaymentStrategy {
private String cardNumber;
public CreditCardPayment(String cardNumber) {
this.cardNumber = cardNumber;
}
@Override
public void pay(int amount) {
System.out.println("Paid $" + amount + " using Credit Card: " + cardNumber);
}
}
public class PayPalPayment implements PaymentStrategy {
private String email;
public PayPalPayment(String email) {
this.email = email;
}
@Override
public void pay(int amount) {
System.out.println("Paid $" + amount + " using PayPal: " + email);
}
}
public class CryptoPayment implements PaymentStrategy {
private String walletAddress;
public CryptoPayment(String walletAddress) {
this.walletAddress = walletAddress;
}
@Override
public void pay(int amount) {
System.out.println("Paid $" + amount + " using Crypto Wallet: " + walletAddress);
}
}
β 3. Context Class
public class PaymentContext {
private PaymentStrategy strategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void pay(int amount) {
if (strategy == null) {
throw new IllegalStateException("Payment Strategy not set");
}
strategy.pay(amount);
}
}
π» Client Code
public class StrategyDemo {
public static void main(String[] args) {
PaymentContext context = new PaymentContext();
context.setPaymentStrategy(new CreditCardPayment("1234-5678-9012-3456"));
context.pay(500);
context.setPaymentStrategy(new PayPalPayment("user@example.com"));
context.pay(300);
context.setPaymentStrategy(new CryptoPayment("0xA1B2C3D4E5F6"));
context.pay(1000);
}
}
π§ͺ Output
Paid $500 using Credit Card: 1234-5678-9012-3456
Paid $300 using PayPal: user@example.com
Paid $1000 using Crypto Wallet: 0xA1B2C3D4E5F6
π― Benefits
β
Replaces complex if-else or switch logic
β
Supports Open-Closed Principle
β
Easier to test, maintain, and extend
β
Promotes flexible design
βοΈ Java Libraries Using Strategy
-
ComparatorinCollections.sort()uses Strategy pattern.
Collections.sort(list, new MyCustomComparator());
π§ Summary
| Feature | Strategy Pattern |
|---|---|
| Pattern Type | Behavioral |
| Main Idea | Define a family of algorithms, encapsulate each, and make them interchangeable |
| Use Cases | Payment processing, file compression, data encryption, sorting, etc. |
π§± Want a UML for reference? Hereβs a quick text version:
+----------------------+
| PaymentStrategy |<-----------+
+----------------------+ |
| +pay(amount): void | |
+----------------------+ |
^ |
| |
+-------------------+ +--------------------+
| CreditCardPayment | | PayPalPayment |
+-------------------+ +--------------------+
^ ^
| |
(Used by) (Used by)
| |
+----------------------+
| PaymentContext |
+----------------------+
| -strategy: Strategy |
| +setStrategy(s) |
| +pay(amount) |
+----------------------+
π Up Next for Day 6: Weβve done Strategy, Decorator, Singleton, Factory, Builder β want to explore Adapter, Chain of Responsibility, State, or Facade next?
Let me know and Iβll get that day rolling!
Top comments (0)