Command Pattern

Command Pattern

Welcome to the lesson on the Command Pattern! This pattern is an essential part of Behavioral Design Patterns and focuses on encapsulating a request as an object. In this way, you can parameterize clients with different requests, queue them, log them, and even support undo operations. It's commonly used in scenarios where you need to decouple the object that invokes an operation from the object that performs it.

What You Will Learn

In this lesson, you will:

  • Understand the basics of the Command Pattern.
  • Learn how to implement this pattern in Java.
  • Recognize the significance of the Command Pattern in real-world applications.

Implementing the Command Pattern

The Command Pattern is a behavioral design pattern that turns a request into a stand-alone object that contains all the information about the request. This transformation allows you to parameterize methods with different requests, queue requests, and log their execution, among other things. At its core, it decouples the object that initiates an action from the object that performs the action.

Let's break down the implementation step-by-step using our example of a remote control for a light. We'll create commands to turn the light on and off, demonstrating the flexibility and reusability of the Command Pattern.

Step 1: Define the Command Interface

public interface Command {
    void execute();
}

The Command interface defines a method called execute, which encapsulates an action. Any class implementing this interface must provide an implementation for the execute method.

Step 2: Implement the Receiver Class

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

The Light class is our receiver. It contains the business logic to turn the light on or off.

Step 3: Implement Concrete Command for Turning the Light On

public class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

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

The LightOnCommand class implements the Command interface. It has a reference to the Light object and calls its on method when execute is invoked.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal