Encapsulates a request as an object, allowing parameterization, queuing, and undo.
Turns actions into first-class objects.
abstract class Command {
void execute();
void undo();
}
class Light {
void on() => print('Light on');
void off() => print('Light off');
}
class LightOnCommand implements Command {
final Light _light;
LightOnCommand(this._light);
@override
void execute() => _light.on();
@override
void undo() => _light.off();
}
class Remote {
final List<Command> _history = [];
void press(Command cmd) {
cmd.execute();
_history.add(cmd);
}
void undoLast() => _history.removeLast().undo();
}
// Usage
final remote = Remote();
remote.press(LightOnCommand(Light())); // Light on
remote.undoLast(); // Light off