Junior — Middle
Do you apply the Command pattern when developing your solutions?
sobes.tech AI
Answer from AI
Yes, I apply the Command pattern to encapsulate requests or operations into objects, which simplifies managing actions, their undoing, and re-execution. For example, in Java, you can create a Command interface with an execute() method, and implement this interface in specific command classes. This helps separate the sender of the command from its receiver and improves code extensibility.
interface Command {
void execute();
}
class LightOnCommand implements Command {
Light light;
LightOnCommand(Light light) { this.light = light; }
public void execute() { light.on(); }
}
class RemoteControl {
Command slot;
void setCommand(Command command) { slot = command; }
void buttonPressed() { slot.execute(); }
}
This approach is useful for implementing menus, task queues, and undo operations.