Lecture 31: Strategy Design Pattern in Spring

BMC201 - Web Technology

Dr. Prashant Kumar Nag

2026-03-17

Lecture 31

Strategy Design Pattern in Spring

Week 8 | Unit IV: Spring Framework Basics
BMC201 - Web Technology
Dr. Prashant Kumar Nag, Assistant Professor

Learning Objectives


  • Understand Strategy pattern
  • Encapsulate interchangeable algorithms
  • Wire and select strategy at runtime

Prerequisites


  • Core Java OOP concepts and interface-based design
  • Basic understanding of Servlets/JSP request flow from Unit III
  • Revision of Lecture 30 before moving into Strategy Design Pattern in Spring

Syllabus Mapping


  • Unit IV topic focus: Strategy Design Pattern in Spring
  • CO alignment: implementation understanding + architecture reasoning
  • Assessment alignment: short definitions + long implementation/design questions

Agenda


  • 5-minute recap from previous lecture
  • Concept deep dive: Strategy Design Pattern in Spring
  • Code/configuration walkthrough and output analysis
  • Debug checklist and exam-oriented summary

Introduction


Strategy isolates behavior variants behind one contract.

Think About It


Can pricing logic switch without changing controller?

What Is Strategy Pattern?


Strategy Pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable.

Key Principles:

  • Define a family of algorithms with a common interface
  • Encapsulate each algorithm in a separate class
  • Make algorithms interchangeable at runtime
  • Client code depends on abstraction, not concrete implementations

The strategy pattern enables selecting algorithm behavior at runtime.

Intent of Strategy Pattern


Problem: When you have multiple ways to perform an operation and need to switch between them dynamically without complex conditional logic.

Solution: Extract varying behaviors into separate strategy classes that implement a common interface, then inject the appropriate strategy.

Benefits:

  • Eliminates conditional statements (if/else, switch)
  • Easy to add new algorithms without modifying existing code (Open-Closed Principle)
  • Strategies are reusable across different contexts
  • Algorithm implementation details are hidden from clients

Strategy Pattern Structure


The pattern has three main components:

Component Role Example
Strategy Interface Defines common contract PaymentStrategy
Concrete Strategies Implement specific algorithms CreditCardPayment, UpiPayment
Context Uses a strategy instance PaymentProcessor

Spring’s DI makes strategy injection and switching seamless.

Code Without Strategy Pattern


// Tightly coupled pricing logic with conditionals
@Service
public class OrderService {
    public double calculateTotal(Order order, String customerType) {
        double subtotal = order.getSubtotal();
        
        // Complex conditional logic
        if (customerType.equals("PREMIUM")) {
            return subtotal * 0.80;  // 20% discount
        } else if (customerType.equals("REGULAR")) {
            return subtotal * 0.95;  // 5% discount
        } else if (customerType.equals("NEW")) {
            return subtotal * 0.90;  // 10% discount
        } else {
            return subtotal;  // No discount
        }
        // Adding new customer type requires modifying this method
    }
}

This violates Open-Closed Principle and creates maintenance issues.

Code With Strategy Pattern


// Strategy interface
public interface PricingStrategy {
    double calculatePrice(double amount);
}

// Concrete strategies
@Component("premiumPricing")
public class PremiumPricing implements PricingStrategy {
    public double calculatePrice(double amount) {
        return amount * 0.80;  // 20% discount
    }
}

@Component("regularPricing")
public class RegularPricing implements PricingStrategy {
    public double calculatePrice(double amount) {
        return amount * 0.95;  // 5% discount
    }
}

// Context using strategy
@Service
public class OrderService {
    private PricingStrategy pricingStrategy;
    
    @Autowired
    public void setPricingStrategy(@Qualifier("premiumPricing") PricingStrategy strategy) {
        this.pricingStrategy = strategy;
    }
    
    public double calculateTotal(Order order) {
        return pricingStrategy.calculatePrice(order.getSubtotal());
    }
}

Benefits in Spring Context


Spring makes Strategy pattern implementation elegant:

  • No conditional logic — behavior selected through configuration
  • Easy testing — mock strategies for unit tests
  • Runtime switching — change strategy without recompiling
  • Clean separation — each algorithm in its own class
// Testing with mock strategy
@Test
public void testOrderCalculation() {
    OrderService service = new OrderService();
    service.setPricingStrategy(amount -> amount * 0.5);  // Test strategy
    assertEquals(50.0, service.calculateTotal(new Order(100)));
}

Spring’s @Qualifier enables selecting strategy by name.

@Qualifier for Strategy Selection


Using @Qualifier to select specific strategy:

@Service
public class PaymentProcessor {
    private final PaymentStrategy strategy;
    
    // Select specific strategy by qualifier name
    @Autowired
    public PaymentProcessor(@Qualifier("upiPayment") PaymentStrategy strategy) {
        this.strategy = strategy;
    }
    
    public void processPayment(double amount) {
        strategy.pay(amount);
    }
}

Alternative approaches:

  • Use @Primary to mark default strategy
  • Use @Profile to select strategy by environment
  • Use configuration properties for dynamic selection

Dynamic Strategy Selection


@Service
public class PaymentService {
    private final Map<String, PaymentStrategy> strategies;
    
    @Autowired
    public PaymentService(List<PaymentStrategy> strategyList) {
        strategies = strategyList.stream()
            .collect(Collectors.toMap(
                s -> s.getClass().getSimpleName(),
                s -> s
            ));
    }
    
    public void processPayment(String method, double amount) {
        PaymentStrategy strategy = strategies.get(method + "Strategy");
        if (strategy == null) {
            throw new IllegalArgumentException("Unknown payment method");
        }
        strategy.pay(amount);
    }
}

Spring auto-wires all strategy implementations into a List/Map.

Real World: Notification Strategies


// Strategy interface
public interface NotificationStrategy {
    void send(String message, String recipient);
}

// Email strategy
@Component
public class EmailNotification implements NotificationStrategy {
    public void send(String message, String recipient) {
        System.out.println("Sending email to " + recipient + ": " + message);
        // Email sending logic
    }
}

// SMS strategy
@Component
public class SmsNotification implements NotificationStrategy {
    public void send(String message, String recipient) {
        System.out.println("Sending SMS to " + recipient + ": " + message);
        // SMS sending logic
    }
}

// Push notification strategy
@Component
public class PushNotification implements NotificationStrategy {
    public void send(String message, String recipient) {
        System.out.println("Sending push notification to " + recipient);
        // Push notification logic
    }
}

Notification Service Using Strategy


@Service
public class NotificationService {
    private final Map<String, NotificationStrategy> strategies;
    
    @Autowired
    public NotificationService(List<NotificationStrategy> notificationStrategies) {
        this.strategies = new HashMap<>();
        for (NotificationStrategy strategy : notificationStrategies) {
            String name = strategy.getClass().getSimpleName()
                .replace("Notification", "").toLowerCase();
            strategies.put(name, strategy);
        }
    }
    
    public void notify(String channel, String message, String recipient) {
        NotificationStrategy strategy = strategies.get(channel);
        if (strategy != null) {
            strategy.send(message, recipient);
        } else {
            throw new IllegalArgumentException("Unknown channel: " + channel);
        }
    }
}

// Usage
notificationService.notify("email", "Welcome!", "user@example.com");
notificationService.notify("sms", "OTP: 1234", "+1234567890");

Environment-Based Strategy Selection


Use @Profile to activate strategies by environment:

// Development discount strategy
@Component
@Profile("dev")
public class DevDiscountStrategy implements PricingStrategy {
    public double calculatePrice(double amount) {
        return amount * 0.50;  // 50% off for testing
    }
}

// Production discount strategy
@Component
@Profile("prod")
public class ProdDiscountStrategy implements PricingStrategy {
    public double calculatePrice(double amount) {
        return amount * 0.95;  // 5% off
    }
}

Set active profile: spring.profiles.active=prod in application.properties

Only the strategy matching the active profile gets instantiated.

Core Concept Summary


Strategy Pattern in Three Steps:

  1. Define interface — Common contract for all algorithms
  2. Implement strategies — Each algorithm in separate class with @Component
  3. Inject strategy — Use @Autowired with optional @Qualifier

Spring enables: - Automatic strategy discovery via component scanning - Flexible injection using qualifiers, profiles, or collections - Easy switching without code changes

Define strategy interface and inject concrete strategy

Strategy vs Factory Pattern


Aspect Strategy Pattern Factory Pattern
Intent Algorithm selection at runtime Object creation
Focus Behavior variation Instance creation
Client Knowledge Knows strategy interface May not know concrete type
When to Use Multiple algorithms for same task Multiple types to instantiate
Spring Usage @Qualifier, @Profile injection BeanFactory, FactoryBean

Often used together: Factory creates strategy instances, context uses them.

Advanced Strategy: Sorting


public interface SortingStrategy<T> {
    List<T> sort(List<T> items, Comparator<T> comparator);
}

@Component("quickSort")
public class QuickSortStrategy<T> implements SortingStrategy<T> {
    public List<T> sort(List<T> items, Comparator<T> comparator) {
        List<T> result = new ArrayList<>(items);
        // Quick sort implementation
        return result;
    }
}

@Component("mergeSort")
public class MergeSortStrategy<T> implements SortingStrategy<T> {
    public List<T> sort(List<T> items, Comparator<T> comparator) {
        List<T> result = new ArrayList<>(items);
        // Merge sort implementation
        return result;
    }
}

@Service
public class DataProcessor {
    @Autowired
    @Qualifier("quickSort")
    private SortingStrategy<String> sortStrategy;
    
    public List<String> processData(List<String> data) {
        return sortStrategy.sort(data, String::compareTo);
    }
}

Strategy Pattern Best Practices


DO:

  • Use meaningful names for strategy components (@Component("premiumPricing"))
  • Keep strategy interface focused on single responsibility
  • Make strategies stateless when possible for thread safety
  • Use @Qualifier for explicit strategy selection
  • Group related strategies in same package

DON’T:

  • Don’t mix business logic into strategy selection code
  • Avoid strategies with many dependencies (violates SRP)
  • Don’t hardcode strategy names in multiple places
  • Avoid mutable state in strategy classes

Common Strategy Pattern Mistakes


Mistake 1: Forgetting @Component on strategy

// ❌ Wrong - Strategy not discoverable
public class FastShipping implements ShippingStrategy { }

// ✅ Correct
@Component
public class FastShipping implements ShippingStrategy { }

Mistake 2: Qualifier mismatches

// ❌ Wrong - Qualifier doesn't match component name
@Component("fast")
public class FastShipping implements ShippingStrategy { }

@Autowired
@Qualifier("fastShipping")  // Mismatch!
private ShippingStrategy shipping;

Mistake 3: Strategies with state instead of stateless

// ❌ Wrong - Mutable state in singleton strategy
@Component
public class TaxStrategy implements PricingStrategy {
    private double lastCalculation;  // State makes it non-thread-safe
}

Testing Strategy Pattern


@SpringBootTest
public class PricingStrategyTest {
    
    @Test
    public void testPremiumPricing() {
        PricingStrategy strategy = new PremiumPricing();
        assertEquals(80.0, strategy.calculatePrice(100.0));
    }
    
    @Test
    public void testOrderServiceWithStrategy() {
        OrderService service = new OrderService();
        
        // Inject test strategy
        service.setPricingStrategy(amount -> amount * 0.5);
        
        Order order = new Order(200.0);
        assertEquals(100.0, service.calculateTotal(order));
    }
    
    @Test
    public void testDynamicStrategySelection() {
        // Mock multiple strategies
        List<PaymentStrategy> strategies = Arrays.asList(
            new CreditCardPayment(),
            new UpiPayment()
        );
        
        PaymentService service = new PaymentService(strategies);
        assertDoesNotThrow(() -> service.processPayment("CreditCard", 100));
    }
}

Code Walkthrough: Complete Example


// 1. Define strategy interface
public interface PricingStrategy {
    double calculatePrice(double amount);
}

// 2. Create concrete strategies
@Component("premiumPricing")
public class PremiumPricing implements PricingStrategy {
    public double calculatePrice(double amount) { return amount * 0.80; }
}

@Component("regularPricing")
public class RegularPricing implements PricingStrategy {
    public double calculatePrice(double amount) { return amount * 0.95; }
}

// 3. Use in service with dependency injection
@Service
public class OrderService {
    @Autowired @Qualifier("premiumPricing")
    private PricingStrategy pricingStrategy;
    
    public double calculateTotal(Order order) {
        return pricingStrategy.calculatePrice(order.getSubtotal());
    }
}

Memory Booster


Syllabus memory points for Strategy Design Pattern in Spring:

  • Core recall: interface-based interchangeable algorithms
  • Exam compare: Hardcoded conditional logic vs strategy selection
  • Practical anchor: Create two strategies and switch implementation at runtime

Live Demo


Live implementation for Strategy Design Pattern in Spring:

?? Open Demo: Lecture 31 - Strategy Design Pattern in Spring

Demo checklist: - implement the key flow for this lecture - verify expected output for one success case - trigger one failure case and explain the fix

Resources & References


Structured Debug Checklist


  1. verify the primary API usage for Strategy Design Pattern in Spring is correct (imports, method names, config)
  2. check request/bean/session flow and object lifecycle assumptions
  3. inspect server logs for the first exception (not just the final symptom)
  4. reproduce one failing case and one passing case before finalizing fixes

Exam Preparation Questions: Short


  • Define Strategy Design Pattern in Spring with one practical use case.
  • Write/identify the key API or construct: interface-based interchangeable algorithms.
  • Differentiate: Hardcoded conditional logic vs strategy selection.
  • Mention one common implementation error and correction.

Exam Preparation Questions: Long


  • Explain Strategy Design Pattern in Spring with architecture/flow and implementation steps.
  • Write a structured answer comparing two approaches used in this topic.
  • Discuss debugging strategy for this topic with likely failure points.

Practice Task


  • Implement: Create two strategies and switch implementation at runtime.
  • Add console/log output to validate flow step-by-step.
  • Document one bug you encountered and the exact fix.

Checklist


Can you:

  • explain Strategy Design Pattern in Spring in your own words?
  • implement a basic example end-to-end?
  • identify and fix one common runtime issue?

Next Lecture


  • Topic: Lecture 32 - AOP & Bean Configuration Styles (XML and Annotation)
  • Preparation required: revise this lecture summary and code walkthrough

Questions?

Next: Lecture 32