The Command Pattern encapsulates a request as an object, allowing you to parameterize clients with different requests, queue or log them, and support undo operations. In this example, we build a Switch that can control multiple devices (a Light and a Fan) without depending on their concrete interfaces.
Devices such as lights and fans have different interfaces (turnOn() vs startRotate()).
A single switch should be able to control either device, but it cannot depend directly on their implementations.
The Command Pattern introduces a Command interface with an execute() method.
Concrete command classes wrap the receiver objects and translate generic Switch requests into device-specific actions.
package com.java.behavioral.command;
public interface Command {
void execute();
}
class Light {
public void turnOn() { System.out.println("Light is on"); }
public void turnOff() { System.out.println("Light is off"); }
}
class Fan {
public void startRotate() { System.out.println("Fan is rotating"); }
public void stopRotate() { System.out.println("Fan is not rotating"); }
}
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light l) { light = l; }
public void execute() { light.turnOn(); }
}
class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light l) { light = l; }
public void execute() { light.turnOff(); }
}
class FanOnCommand implements Command {
private Fan fan;
public FanOnCommand(Fan f) { fan = f; }
public void execute() { fan.startRotate(); }
}
class FanOffCommand implements Command {
private Fan fan;
public FanOffCommand(Fan f) { fan = f; }
public void execute() { fan.stopRotate(); }
}
class Switch {
private Command upCommand, downCommand;
public Switch(Command up, Command down) {
this.upCommand = up;
this.downCommand = down;
}
public void flipUp() { upCommand.execute(); }
public void flipDown() { downCommand.execute(); }
}
public class TestCommand {
public static void main(String[] args) {
Light light = new Light();
Switch lightSwitch = new Switch(
new LightOnCommand(light),
new LightOffCommand(light)
);
lightSwitch.flipUp();
lightSwitch.flipDown();
Fan fan = new Fan();
Switch fanSwitch = new Switch(
new FanOnCommand(fan),
new FanOffCommand(fan)
);
fanSwitch.flipUp();
fanSwitch.flipDown();
}
}
Light is on Light is off Fan is rotating Fan is not rotating