Middle
Do you use the Command pattern in your work?
sobes.tech AI
Answer from AI
Yes, I use it. The Command pattern encapsulates a request as an object, allowing clients to be parameterized with different requests, queue or log requests, and support undo operations.
I apply it in the following cases:
- Implementing undo/redo operations: Each command stores information needed to execute and undo the operation.
- Implementing task queues: Commands are added to a queue and executed in the background or on a schedule.
- Logging operations: Commands can be logged before execution, which helps restore state or debug errors.
- Abstracting method calls: It allows calling methods without explicitly knowing their names or parameters, making client code more flexible.
Example structure:
- Class
Command(interface or abstract class) with the methodexecute(). - Concrete command classes (e.g.,
SaveCommand,OpenCommand,PrintCommand) implementingCommand. - Class
Invoker(initiator), which calls theexecute()method on the command object. - Class
Receiver(receiver), which performs the actual work (business logic).
// Command interface
interface Command {
void execute();
}
// Concrete save file command
class SaveCommand implements Command {
private FileSystemReceiver fileSystem; // Receiver
public SaveCommand(FileSystemReceiver fs) {
this.fileSystem = fs;
}
@Override
public void execute() {
fileSystem.saveFile();
}
}
// Concrete open file command
class OpenCommand implements Command {
private FileSystemReceiver fileSystem;
public OpenCommand(FileSystemReceiver fs) {
this.fileSystem = fs;
}
@Override
public void execute() {
fileSystem.openFile();
}
}
// Receiver
interface FileSystemReceiver {
void openFile();
void saveFile();
}
// Windows-specific receiver
class WindowsFileSystemReceiver implements FileSystemReceiver {
@Override
public void openFile() {
System.out.println("Opening file in Windows...");
}
@Override
public void saveFile() {
System.out.println("Saving file in Windows...");
}
}
// Invoker
class FileInvoker {
private Command command;
public FileInvoker(Command command) {
this.command = command;
}
public void executeCommand() {
this.command.execute();
}
}
// Usage example
public class CommandPatternDemo {
public static void main(String[] args) {
// Create receiver
FileSystemReceiver fs = new WindowsFileSystemReceiver();
// Create commands, passing the receiver
Command openCmd = new OpenCommand(fs);
Command saveCmd = new SaveCommand(fs);
// Create invokers and associate them with commands
FileInvoker openInvoker = new FileInvoker(openCmd);
FileInvoker saveInvoker = new FileInvoker(saveCmd);
// Execute commands via invokers
openInvoker.executeCommand();
saveInvoker.executeCommand();
}
}