📅 Week-3 (Day-5) Understanding the Command Design Pattern: Real-World Examples and Code

Payal KumariPayal Kumari
5 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 Command Design Pattern?

The Command Pattern is like giving instructions to your smart devices 🏡 — but in a way that’s reusable, organized, and flexible.

It’s a behavioral design pattern that encapsulates a request as an object, allowing you to queue, execute, and even undo actions — just like a remote control for your home appliances.

(Hindi: Command Design Pattern ek design technique hai jisme hum kisi bhi action (jaise light on/off karna) ko ek object ke form mein store kar lete hain. Isse hum wo command future mein reuse, undo, ya queue bhi kar sakte hain — bilkul ek smart remote ki tarah jo har device ke liye kaam karta hai.)

Tech Note:
"Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations."
(For those preparing for technical interviews or formal definitions!)

💠 Real-Life Example: Smart Home Automation

Imagine you have a smart home setup:

  • You want to turn the lights ON, switch the fan OFF, and undo the last action…

  • Instead of hardcoding all actions, you create command objects for each action.

So you have:

🔘 LightOnCommand
🔘 FanOffCommand
🔘 UndoLastCommand

Each of these commands knows what device to control and how to perform the action, but your main controller (called the Invoker) doesn't care about the actual device — it just runs the command when needed.

(Hindi: Sochiye aapke paas ek smart home remote hai — aap har device ke liye ek alag command object banate ho. Jaise "LightOnCommand", "FanOffCommand", etc. Fir aapka remote (Invoker) sirf commands execute karta hai bina yeh jaane ki actual kaam kaise ho raha hai.)

💠Why Use the Command Pattern?

  • Decouples objects – Controller doesn’t need to know how device works

  • Reusable & Extensible – Add new commands without changing old code

  • Undo functionality – You can reverse actions easily

  • Perfect for automation systems, IoT platforms, task schedulers

(Hindi:
✅ Har device ko remote se alag kar deta hai
✅ Naye actions add karna easy hota hai
✅ Undo feature banana possible hota hai
✅ Automation ya IoT system ke liye perfect hai)

💠UML Diagrams

💠Code

// ----------------------------
// Command Interface
// ----------------------------
interface Command {
    void execute();
    void undo();
}

// ----------------------------
// Receivers
// ----------------------------
class Light {
    public void on()  {
        System.out.println("Light is ON");
    }
    public void off() {
        System.out.println("Light is OFF");
    }
}

class Fan {
    public void on()  {
        System.out.println("Fan is ON");
    }
    public void off() {
        System.out.println("Fan is OFF");
    }
}

// ----------------------------
// Concrete Command for Light
// ----------------------------
class LightCommand implements Command {
    private Light light;

    public LightCommand(Light l) {
        this.light = l;
    }

    public void execute() {
        light.on();
    }

    public void undo() {
        light.off();
    }
}

// ----------------------------
// Concrete Command for Fan
// ----------------------------
class FanCommand implements Command {
    private Fan fan;

    public FanCommand(Fan f) {
        this.fan = f;
    }

    public void execute() {
        fan.on();
    }

    public void undo() {
        fan.off();
    }
}

// ----------------------------
// Invoker: Remote Controller with static array of 4 buttons
// ----------------------------
class RemoteController {
    private static final int numButtons = 4;
    private Command[] buttons;
    private boolean[] buttonPressed;

    public RemoteController() {
        buttons = new Command[numButtons];
        buttonPressed = new boolean[numButtons];
        for (int i = 0; i < numButtons; i++) {
            buttons[i] = null;
            buttonPressed[i] = false;  // false = off, true = on
        }
    }

    public void setCommand(int idx, Command cmd) {
        if (idx >= 0 && idx < numButtons) {
            buttons[idx] = cmd;
            buttonPressed[idx] = false;
        }
    }

    public void pressButton(int idx) {
        if (idx >= 0 && idx < numButtons && buttons[idx] != null) {
            if (!buttonPressed[idx]) {
                buttons[idx].execute();
            } else {
                buttons[idx].undo();
            }
            buttonPressed[idx] = !buttonPressed[idx];
        } else {
            System.out.println("No command assigned at button " + idx);
        }
    }
}

// ----------------------------
// Main Application
// ----------------------------
public class CommandPattern {
    public static void main(String[] args) {
        Light livingRoomLight = new Light();
        Fan ceilingFan = new Fan();

        RemoteController remote = new RemoteController();

        remote.setCommand(0, new LightCommand(livingRoomLight));
        remote.setCommand(1, new FanCommand(ceilingFan));

        // Simulate button presses (toggle behavior)
        System.out.println("--- Toggling Light Button 0 ---");
        remote.pressButton(0);  // ON
        remote.pressButton(0);  // OFF

        System.out.println("--- Toggling Fan Button 1 ---");
        remote.pressButton(1);  // ON
        remote.pressButton(1);  // OFF

        // Press unassigned button to show default message
        System.out.println("--- Pressing Unassigned Button 2 ---");
        remote.pressButton(2);
    }
}

💠Final Thoughts

The Command Pattern is not just theory — it’s the real-world logic behind smart devices, task queues, game controls, and more.
If you're serious about building scalable, maintainable, and decoupled systems, this is a pattern you must know! 🌟

(Hindi: Command Pattern sirf ek concept nahi, balki smart homes, task automation, aur game systems ka real-world base hai. Agar aap scalable aur clean systems banana chahte hain, toh ye pattern zaroor seekhiye.)

Week - 3 ( Day-5 ) 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 :- https://www.youtube.com/@CoderArmy9 . 🙌

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

✍️ Payal Kumari 👩‍💻

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.