Command Pattern: Classic Version
Command Pattern: Classic Version
Command Pattern: Classic Version
Tags
"Encapsulate all the data related to command in one object" → set of methods,
their parameters, and one or more objects Receiver) which these methods
belong to.
The important point about decoupling is if you had to change any of these
values, you only have to change one class.
Classic version
The classic version of the Command pattern has the following elements:
Command Pattern 1
The Client creates an object of Receiver and a ConcreteCommand and sets up the
Invoker to execute the command. Each type of ConcreteCommand (e.g.
CreateFileCommand, RemoveFileCommand) has a set of fields which represent
the params. A command calls one or more methods of the Receiver to execute
concrete actions to change the state of the application.
Example
@Override
public void execute() {
light.lightOn();
}
}
Command Pattern 2
this.light = light;
}
@Override
public void execute() {
light.lightOff();
}
}
// receiver
public class Light {
// invoker
public class Controller {
controller.setCommand(lightsOn);
controller.executeCommand();
controller.setCommand(lightsOff);
controller.executeCommand();
}
}
Command Pattern 3
Additional options
The Command pattern can be used together with the following options:
Applicability
GUI buttons and menu items. In Swing programming, an Action is a command
object. In addition to the ability to perform the desired command, an Action
may have an associated icon, a keyboard shortcut, tooltip text, and so on.
Command Pattern 4