Middle
What is the Command pattern used for?
sobes.tech AI
Answer from AI
The Command pattern is used to encapsulate a request as an object, allowing parameterization of clients with different requests, queuing or logging requests, and supporting undo operations.
Main components of the pattern:
Command: An interface or abstract class declaring a method for executing a request.ConcreteCommand: Classes implementingCommand, linking the Receiver with an action. EachConcreteCommandcontains a reference to theReceiver.Invoker: A class that initiates the command. It holds a reference to aCommandbut does not know the details of the operation.Receiver: A class that performs the actual action.ConcreteCommandcalls methods on theReceiver.
Example of usage for implementing media player control buttons:
// Receiver
class MediaPlayer {
public void play() {
System.out.println("Playing media...");
}
public void stop() {
System.out.println("Stopping media...");
}
}
// Command
interface MediaCommand {
void execute();
}
// Concrete Commands
class PlayCommand implements MediaCommand {
private MediaPlayer player;
public PlayCommand(MediaPlayer player) {
this.player = player;
}
@Override
public void execute() {
player.play();
}
}
class StopCommand implements MediaCommand {
private MediaPlayer player;
public StopCommand(MediaPlayer player) {
this.player = player;
}
@Override
public void execute() {
player.stop();
}
}
// Invoker
class MediaController {
private MediaCommand command;
public void setCommand(MediaCommand command) {
this.command = command;
}
public void pressButton() {
if (command != null) {
command.execute();
}
}
}
// Client Code
class Client {
public static void main(String[] args) {
MediaPlayer player = new MediaPlayer();
PlayCommand playCommand = new PlayCommand(player);
StopCommand stopCommand = new StopCommand(player);
MediaController controller = new MediaController();
controller.setCommand(playCommand);
controller.pressButton(); // Output: Playing media...
controller.setCommand(stopCommand);
controller.pressButton(); // Output: Stopping media...
}
}
Advantages:
- Separates the sender of a request from its execution.
- Easily adds new commands without changing the Invoker.
- Supports undo operations (if implemented).
- Can be used to create macros (sequence of commands) and log operations.