Command Pattern Explained: Theory, Java Code, and Real‑World Scenarios
This article introduces the Command pattern, describing how encapsulating each action as a command object decouples callers from executors, and demonstrates its use through real‑world examples like remote controls and editors, followed by a complete Java implementation, common business scenarios, and a brief pros‑cons analysis.
What is the Command Pattern?
Each operation is encapsulated in an independent command object. The caller sends a command without needing to know the executor, enabling queuing, undo, and repeat execution.
Purpose: decouple initiator from executor; commands can be stored, rolled back, or executed in bulk.
Typical scenarios
Remote control: buttons are commands, TV is the receiver; channel change, volume adjust are separate commands that can record history.
Software: editor undo/redo, batch task queues, scheduled jobs, button click actions.
Order processing: place, cancel, refund operations wrapped as commands for unified scheduling.
Java implementation (TV remote example)
1. Command interface
public interface Command {
void execute();
// undo operation
void undo();
}2. Receiver – TV
public class TV {
public void open(){
System.out.println("电视开机");
}
public void close(){
System.out.println("电视关机");
}
}3. Concrete commands
// Open command
public class OpenTVCommand implements Command{
private TV tv;
public OpenTVCommand(TV tv){
this.tv = tv;
}
@Override
public void execute() {
tv.open();
}
@Override
public void undo() {
tv.close();
}
}
// Close command
public class CloseTVCommand implements Command{
private TV tv;
public CloseTVCommand(TV tv){
this.tv = tv;
}
@Override
public void execute() {
tv.close();
}
@Override
public void undo() {
tv.open();
}
}4. Invoker – RemoteControl
public class RemoteControl {
private Command command;
public void setCommand(Command command){
this.command = command;
}
// press button
public void press(){
command.execute();
}
// undo previous action
public void back(){
command.undo();
}
}5. Test driver
public class Test {
public static void main(String[] args) {
TV tv = new TV();
RemoteControl remote = new RemoteControl();
// execute open
remote.setCommand(new OpenTVCommand(tv));
remote.press();
// undo open, resulting in close
remote.back();
}
}Common business scenarios
Undo/redo needed: document editors, form operation rollback.
Task queues, scheduled or asynchronous batch operations; commands can be cached and queued.
GUI button or menu click events, each click encapsulated as a separate command.
Log operation history for recovery after failures.
Distributed task dispatch, command serialization for transmission.
Advantages and disadvantages
Advantages: decouples operation, supports rollback, enables batch commands.
Disadvantages: each action requires a new command class, increasing the number of classes.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
liandk
Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
