-
- Intention
- Applicability
- Structure
- Realize
- Effect
- Reference
Intention
Encapsulates the request as an object, the customer accepts the request parameters, can queue the request or logs the request log, and can support the undo operation
Applicability
- Abstract the action to be executed to parameterize an object. The command pattern is an object-oriented alternative to the callback mechanism.
- Specify, arrange, and execute requests at different times
- Support Cancel operation
- Support for modifying logs
- Support Transactions
Structure
Realize
Remote control of a lamp is realized by using the remote control. The lights are on and off with two operations.
class Light{Public void on() {Console.WriteLine (" Light was on"); }Public void Off() {Console.WriteLine ("Light is Off"); } }
First, the Operation class or interface is abstracted.
Public Interface ICommand{ void Execute() ; void Undo() ;//Revoke}
This opens, closes two operation requests to encapsulate, the operation needs an object as the initialization parameter
class Lightoncommand:ICommand{PrivateLight _light;Public lightoncommand(light) { This. _light = Light; }Public void Execute() {_light. On (); }Public void Undo() {_light. Off (); } }class Lightoffcommand:ICommand{PrivateLight _light;Public lightoffcommand(light) { This. _light = Light; }Public void Execute() {_light. Off (); }Public void Undo() {_light. On (); } }
The remote control accepts the request as an initialization parameter
class Simpleremotecontrol{PrivateICommand _onslot;PrivateICommand _offslot;PrivateICommand _lastcommand;//Record last action request Public void setcommand(ICommand oncommand,icommand offcommand) {_onslot = OnCommand; _offslot = Offcommand; }Public void onbuttonwaspressed() {_onslot.execute (); _lastcommand = _onslot; }Public void offbuttonwaspressed() {_offslot.execute (); _lastcommand = _offslot; }Public void Undo() {_lastcommand.undo (); } }
Parameterize the customer (remote control) with the encapsulated request, allowing the lamp to be controlled, or to encapsulate more operations so that the remote controls other items
class Program{ static void Main(string[] args) {Simpleremotecontrol remote =NewSimpleremotecontrol (); Light light =NewLight (); Lightoncommand Lighton =NewLightoncommand (light); Lightoffcommand Lightoff =NewLightoffcommand (light); Remote. SetCommand (Lighton, Lightoff); Remote. Onbuttonwaspressed (); Remote. Offbuttonwaspressed (); Remote. Undo ();//Undo Previous actionConsole.readkey (); } }
Run results
Effect
- Decouple the object that invokes the operation from the object that knows how to implement the operation
- Multiple commands can be assembled into a composite command
- Add a new command without modifying an existing class
Reference
- "Head First design mode"
- "Design Mode"
Design Pattern C # implementation (15)--Command mode