Behavioral Design Patterns

How does behavioral pattern works

Behavioral Design Patterns โ€” Exhaustive Deep Dive Guide

PART 1: STRATEGY PATTERN

1. Requirement Gathering & Clarification

Imagine you're asked: "Design a payment processing system for an e-commerce platform."

Clarifying questions a Staff Engineer would ask:

  • How many payment methods do we support? (Credit Card, PayPal, UPI, Crypto, etc.)
  • Can the payment method change at runtime based on user selection?
  • Do we need to add new payment methods without modifying existing code?
  • Are there different validation rules per payment method?
  • Do we need fallback strategies if one payment fails?

Core Problem: We have a family of algorithms (payment methods), and we want to select one at runtime without coupling the client to concrete implementations.

2. First Principles Approach

What is Strategy?

Strategy defines a family of algorithms, encapsulates each one, and makes them interchangeable. The algorithm varies independently from the clients that use it.

Without Strategy (the anti-pattern):

public class PaymentProcessor {
    public void pay(String type, double amount) {
        if ("CREDIT_CARD".equals(type)) {
            // credit card logic
        } else if ("PAYPAL".equals(type)) {
            // paypal logic
        } else if ("UPI".equals(type)) {
            // upi logic
        }
        // Every new method โ†’ modify this class โ†’ OCP violation
    }
}

Problems: OCP violation, bloated class, testing nightmare, tight coupling.

1 / 43