DEV Community

Machine coding Master
Machine coding Master

Posted on Originally published at javalld.com

Strategy Pattern in Java LLD: Clean Swappable Algorithms for Machine Coding

Strategy Pattern in Java LLD: Clean Swappable Algorithms for Machine Coding

In LLD interviews at top tech companies, hardcoding conditional logic to handle multiple execution behaviors is an immediate red flag. The Strategy Pattern proves to your interviewer that you can design decoupled, extensible systems that adapt dynamically at runtime without modifying existing, tested code.

The Mistake Most Candidates Make

  • Writing sprawling if-else or switch statements inside context classes to pick algorithms (e.g., routing algorithms, payment methods, compression formats).
  • Violating the Open/Closed Principle by modifying the core orchestrator every time a new business requirement or algorithm emerges.
  • Relying on rigid inheritance hierarchies rather than composition, leading to class explosion and brittle architectures.

The Right Approach

  • Core mental model: Define a family of interchangeable algorithms behind a uniform interface and delegate execution to the injected strategy instance.
  • Key entities/classes: PaymentStrategy, CreditCardPayment, CryptoPayment, CheckoutService.
  • Why it beats the naive approach: It eliminates cyclomatic complexity and allows dynamic, runtime algorithm switching with zero regression risk to the calling class.

The Key Insight (Code)

public class PaymentContext {
    private PaymentStrategy strategy;

    public PaymentContext(PaymentStrategy strategy) {
        this.strategy = strategy;
    }

    public void setStrategy(PaymentStrategy strategy) {
        this.strategy = strategy; // Dynamic runtime swap
    }

    public void executePayment(double amount) {
        this.strategy.pay(amount); // Delegated polymorphism
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Favor composition over inheritance: compose context objects with interchangeable behavioral strategies.
  • Eliminates branching logic (switch/if-else), dramatically lowering cyclomatic complexity and unit test overhead.
  • Strictly adheres to the Open/Closed Principle: add new behaviors by creating new classes without altering existing context implementations.

Shameless plug: javalld.com has full LLD implementations with step-by-step execution traces — free to use while prepping.

Full working implementation with execution trace available at https://javalld.com/learn/strategy-pattern

Top comments (0)