đź“…Week 2 Day 3 - Understanding the Strategy Design Pattern with a Practical Example for Low-Level Design

Payal KumariPayal Kumari
6 min read

NOTE: - I started my 8-week system design journey with Coder Army. I will be journaling every day, recording what I learn, reflecting on it, and sharing it with my network to help newcomers to system design.

đź’ What is the Strategy Design Pattern?

Defines a family of algorithms, puts them into separate classes so that they can be changed at run time.

"Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it."

(Hindi: Strategy Pattern ek family of algorithms define karta hai, har ek algorithm ko alag se encapsulate karta hai, aur unhe interchangeable banata hai. Isse algorithms ko bina client code change kiye easily change kiya ja sakta hai.)

📍 In simple words: It's like having different ways to solve a problem and being able to switch between those ways easily!

📍Real-Life Example:
Think of Google Maps 🗺️ – when you enter a location, it shows:

  • đźš— Driving route

  • đźš¶ Walking path

  • 🚴‍♀️ Cycling option

  • 🚌 Public transport

You choose one based on your need, but the destination remains the same.
Each of these is a strategy, and Google Maps is the context that uses them.

(Hindi : Jaise Google Maps mein aap route select karte ho – car, paidal, cycle ya bus – yeh sab alag-alag strategies hain jo same destination tak pahuchne ke liye hoti hain.)

đź’ Why & When to Use Strategy Pattern?

âś… When you have many similar algorithms (behaviors)
âś… When you want to switch algorithms at runtime
✅ When you want to follow SOLID principles (especially OCP – Open/Closed Principle)

📍 Problem with Inheritance:

  • Code re-use becomes complex

  • Adding new features becomes painful

  • Violates Open/Closed Principle (OCP)

(Hindi : "Inheritance mein baar-baar changes karne padte hain, naye features add karne mein dikkat aati hai, aur code baar-baar break hota hai.")

đź’ How to Implement It Using Clean OOP Principles?

Step 1: Create an interface (common behavior)
Step 2: Write separate classes for different algorithms
Step 3: Use composition to inject behavior into the main class
Step 4: Switch strategy as needed

interface PaymentStrategy {
  void pay(int amount);
}

class CreditCardPayment implements PaymentStrategy {
  public void pay(int amount) { System.out.println("Paid via Credit Card"); }
}

class UpiPayment implements PaymentStrategy {
  public void pay(int amount) { System.out.println("Paid via UPI"); }
}

class ShoppingCart {
  private PaymentStrategy strategy;
  public void setPaymentStrategy(PaymentStrategy strategy) { this.strategy = strategy; }
  public void checkout(int amount) { strategy.pay(amount); }
}

Now you can switch between CreditCardPayment or UpiPayment easily!

đź’ Real-Life Scenario You Can Relate To

Designing Flexible Robots for a Smart Home 🏠

Imagine you are building different types of robots for a smart home system – each robot has different capabilities like:

  • đźš¶ Walking

  • 🗣️ Talking

  • 🛫 Flying

But not all robots need all abilities!
For example:

  • Companion Robot (for kids or elderly): Can walk and talk, but doesn't fly.

  • Worker Robot (used in factories): Can fly (e.g., drone-based) but cannot walk or talk.

📍Problem Without Strategy Pattern

If you used inheritance only, you’d end up with:

  • Long class hierarchies

  • Lots of duplicate code

  • Difficulty in changing a feature without breaking others

Every time you want a new behavior (e.g., silent mode, hovering), you’d have to change the parent class or create multiple subclasses, which is not scalable.

âś… Solution with Strategy Pattern

With Strategy Design Pattern, you can:

  1. Encapsulate each behavior (walk, talk, fly) as separate classes

  2. Assign behaviors to robots dynamically

  3. Add or change behaviors without modifying existing robot classes

📍Code Walkthrough & Explanation

  • CompanionRobot:

Robot robot1 = new CompanionRobot(new NormalWalk(), new NormalTalk(), new NoFly());

📝 Meaning: This robot can walk and talk normally but cannot fly.

  • WorkerRobot:

Robot robot2 = new WorkerRobot(new NoWalk(), new NoTalk(), new NormalFly());

📝 Meaning: This robot only flies and cannot walk or talk. Useful for industrial tasks!

📍Dynamic Behavior Switching

What if your robot upgrades in the future?

You don’t need to change the class! Just set a new strategy:

robot1.flyBehavior = new NormalFly(); // Now CompanionRobot can fly!

"Ab aap apne purane robot mein naya fly wala feature add kar sakte ho bina kisi major change ke."

📍Why It’s Useful

âś… Helps you code to interface not implementation
✅ Follows Open/Closed Principle – open for extension, closed for modification
âś… Super useful in LLD interviews and real-world systems like:

  • Game character behavior switching

  • AI chatbot customization

  • E-commerce discount strategy

📍Key Takeaways

🔹 Encapsulate what varies – Rakho alag jo badalta rehta hai.
🔹 Don’t solve inheritance issues by adding more inheritance
🔹 Code to interfaces, not implementations
🔹 DRY: Don’t Repeat Yourself!

// --- Strategy Interface for Walk ---
interface WalkableRobot {
    void walk();
}

// --- Concrete Strategies for walk ---
class NormalWalk implements WalkableRobot {
    public void walk() {
        System.out.println("Walking normally...");
    }
}

class NoWalk implements WalkableRobot {
    public void walk() {
        System.out.println("Cannot walk.");
    }
}

// --- Strategy Interface for Talk ---
interface TalkableRobot {
    void talk();
}

// --- Concrete Strategies for Talk ---
class NormalTalk implements TalkableRobot {
    public void talk() {
        System.out.println("Talking normally...");
    }
}

class NoTalk implements TalkableRobot {
    public void talk() {
        System.out.println("Cannot talk.");
    }
}

// --- Strategy Interface for Fly ---
interface FlyableRobot {
    void fly();
}

class NormalFly implements FlyableRobot {
    public void fly() {
        System.out.println("Flying normally...");
    }
}

class NoFly implements FlyableRobot {
    public void fly() {
        System.out.println("Cannot fly.");
    }
}

// --- Robot Base Class ---
abstract class Robot {
    protected WalkableRobot walkBehavior;
    protected TalkableRobot talkBehavior;
    protected FlyableRobot flyBehavior;

    public Robot(WalkableRobot w, TalkableRobot t, FlyableRobot f) {
        this.walkBehavior = w;
        this.talkBehavior = t;
        this.flyBehavior = f;
    }

    public void walk() {
        walkBehavior.walk();
    }

    public void talk() {
        talkBehavior.talk();
    }

    public void fly() {
        flyBehavior.fly();
    }

    public abstract void projection(); // Abstract method for subclasses
}

// --- Concrete Robot Types ---
class CompanionRobot extends Robot {
    public CompanionRobot(WalkableRobot w, TalkableRobot t, FlyableRobot f) {
        super(w, t, f);
    }

    public void projection() {
        System.out.println("Displaying friendly companion features...");
    }
}

class WorkerRobot extends Robot {
    public WorkerRobot(WalkableRobot w, TalkableRobot t, FlyableRobot f) {
        super(w, t, f);
    }

    public void projection() {
        System.out.println("Displaying worker efficiency stats...");
    }
}

// --- Main Function ---
public class StrategyDesignPattern {
    public static void main(String[] args) {
        Robot robot1 = new CompanionRobot(new NormalWalk(), new NormalTalk(), new NoFly());
        robot1.walk();
        robot1.talk();
        robot1.fly();
        robot1.projection();

        System.out.println("--------------------");

        Robot robot2 = new WorkerRobot(new NoWalk(), new NoTalk(), new NormalFly());
        robot2.walk();
        robot2.talk();
        robot2.fly();
        robot2.projection();
    }
}

Week - 2 (Day 3) Completed âś… System Design

NOTE : - A big thanks to my mentors Rohit Negi Sir and Aditya Sir for launching this amazing 8-week course absolutely free on YouTube via CoderArmy9 :- youtube.com/@CoderArmy9 . 🙌

👉 Share this blog with your connections! Let’s keep learning, growing, and supporting one another on this journey. 🚀

✍️ Payal Kumari 👩‍💻 Github

Jai Hind 🇮🇳 | #CoderArmy #LearningInPublic #SystemDesign #TechForAll #MentorshipMatters #8weeksLLdChallenge #LowLevelDesign #Code #LLD #OOP

0
Subscribe to my newsletter

Read articles from Payal Kumari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Kumari
Payal Kumari

I'm a passionate full-stack developer with a strong foundation in the MERN stack—building and maintaining scalable web applications using React.js, Node.js, and Next.js. My journey in open source began with Hacktoberfest 2023, where I made four impactful pull requests that sparked a love for collaborative coding, global learning, and open knowledge sharing. Since then, I’ve contributed to and mentored projects in top open source programs like GSSoC’24, SSOC’24, and C4GT’24. As a Google Gen AI Exchange Hackathon ’24 Finalist and Google’s Women Techmakers (WTM) Ambassador, I’ve been privileged to support diverse communities in building meaningful tech solutions. My work as a Top 50 Mentor for GSSoC ’24 reflects my commitment to nurturing new talent in tech. Beyond development, I serve as a Student Career Guide, Profile Building Expert & Evangelist at Topmate.io, where I conduct workshops, guide students through resume building and career strategy, and help mentees navigate open source and tech careers. Recognized among the Top 5% of mentors and featured on “Topmate Discover,” I take pride in making mentorship accessible and impactful. My technical voice has also been acknowledged by LinkedIn, where I’ve earned the Top Voice badge seven times in domains like web development, programming, and software engineering. In addition, I hold LinkedIn Golden Badges for Research Skills, Interpersonal Skills, Critical Thinking, and Teamwork—signaling a well-rounded approach to both individual contribution and team collaboration. Graduating with an MCA from Chandigarh University in 2023, I’ve continued to fuel my curiosity by writing technical articles and sharing practical MERN stack insights across platforms. Whether it’s building polished UIs, optimizing backend performance, or guiding a mentee through their first pull request, I’m driven by the power of community and continuous learning. Let’s connect! I'm open to collaborations, mentorship, or building something impactful together. Reach out to me at kumaripayal7488@gmail.com or visit my profile on Topmate.io.