Command patterns comes under Behavioral design pattern. It encapsulates
the complete request information as an object to defer its execution at later point.
Behaviour & Advantages
Separates the object from its trigger.
Holds complete request information to trigger at later point.
Needs a callback method to trigger execution.
Participants
Command
Abstract interface for command execution.
Concrete Command
An implementation of Command which updates Receiver's state.
Invoker
It hold a reference to Concrete Command and triggers its execution.
Receiver
Its the target object for Concrete Command and receives the action performed.
This example shows a simple CLI (Command Line Interface) implementation where
console (System.out) acts as a Receiver and CLI acts as Invoker.
The CLI supports four commands namely mm (max memory), fm (free memory), tm (total memory) and exit.
These commands output a message to console (Receiver).
A Concrete implementation of command object is defined supporting each command.
@Override public void execute() {
System.exit(0);
}
@Override public String getName() { return "exit";
}
@Override public String getDesc() { return "System Exit";
}
}
Here CLI prints command listing and accepts command name as input.
If user entered command name is available in the command map then triggers the command execution.
Otherwise prints unknown command message to console.
------ CLI Command Listing ------
1. System Max Memory (mm)
2. System Free Memory (fm)
3. System Total Memory (tm)
4. System Exit (exit)
Enter command :
mm
System Max Memory : 66650112 bytes
------ CLI Command Listing ------
1. System Max Memory (mm)
2. System Free Memory (fm)
3. System Total Memory (tm)
4. System Exit (exit)
Enter command :
fm
System Free Memory : 4902592 bytes
------ CLI Command Listing ------
1. System Max Memory (mm)
2. System Free Memory (fm)
3. System Total Memory (tm)
4. System Exit (exit)
Enter command :
tm
System Total Memory : 5177344 bytes
------ CLI Command Listing ------
1. System Max Memory (mm)
2. System Free Memory (fm)
3. System Total Memory (tm)
4. System Exit (exit)
Enter command :
exit