command-pattern
🧩 Concept
🧱 Key Roles
Role
Description
💻 Simple Java Example
// Command interface
interface Command {
void execute();
}
// Receiver
class Light {
void turnOn() { System.out.println("Light is ON"); }
void turnOff() { System.out.println("Light is OFF"); }
}
// Concrete commands
class TurnOnCommand implements Command {
private Light light;
TurnOnCommand(Light light) { this.light = light; }
public void execute() { light.turnOn(); }
}
class TurnOffCommand implements Command {
private Light light;
TurnOffCommand(Light light) { this.light = light; }
public void execute() { light.turnOff(); }
}
// Invoker
class RemoteControl {
private Command command;
void setCommand(Command command) { this.command = command; }
void pressButton() { command.execute(); }
}🧠 Flow Summary (Step-by-Step)
Step
Action
Invoker (Remote)
Command
Receiver (Light)
Output
🪜 Summary
💡 Real-world Analogy
Last updated