Command mode:
Command: encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests or record request logs, and support unrecoverable operations.
Common scenarios &&Advantages:
1. It is easier to design a command line
2. It is easier to log commands
3. The requesting party is allowed to decide whether to reject the request.
4. Supports undo operations and redo operations
5. adding a new command class does not affect other classes.
6. Split the object requesting an operation from the object that knows how to perform an operation.
Demo1:
//Abstract command class
Public abstract class command
{
Protected barbecuer receiver; // BBQ
Public command (barbecuer receiver)
{
This. Cycler = Cycler;
}
Abstract Public void excutecommand (); // execute the command
}
//Barbecue, specific implementation class
Public class barbecuer
{
// Roast mutton. method 1
Public void bakemutton ()
{
Console. writeline ("roast mutton. ");
}
// Roast chicken wings. method 2
Public void bakechickenwing ()
{
Console. writeline ("roast chicken wings. ");
}
}
//Specific command class
// Roast mutton command
Class bakemuttoncommand: Command
{
Public bakemuttoncommand (barbecuer receiver): Base (receiver ER ){}
Public override void excutecommand ()
{
Else er. bakemutton (); // call the specific method passed in the virtual method to execute the specific method
}
}
// Roast chicken wings command
Class bakechickenwingcommand: Command
{
Public bakechickenwingcommand (barbecuer receiver)
: Base (worker ER)
{}
Public override void excutecommand ()
{
Cycler. bakechickenwing ();
}
}
//Attendant
Public class waiter
{
Private ilist <command> order = new list <command> ();
// Set the order
Public void setorder (command)
{
If (command. tostring () = "")
{
Console. writeline ("no chicken wings ");
}
Else
{
Order. Add (command );
Console. writeline ("add order" + command. tostring () + "time" + datetime. Now. tostring ());
}
}
// Cancel the order
Public void cancelorder (command)
{
Order. Remove (command );
Console. writeline ("cancel order" + command. tostring () + "time" + datetime. Now. tostring ());
}
// Notification execution
Public void Policy ()
{
Foreach (command C in order)
{
C. excutecommand ();
}
}
}
//Preparations before opening a shop
Barbecuer boy = new barbecuer ();
Command bakemuttoncommand1 = new bakemuttoncommand (boy );
Command bakemuttoncommand2 = new bakemuttoncommand (boy );
Command bakechickenwingcommand1 = new bakechickenwingcommand (boy );
Waiter girl = new waiter ();
// Open the door for business
Girl. setorder (bakechickenwingcommand1 );
Girl. setorder (bakemuttoncommand1 );
Girl. setorder (bakemuttoncommand2 );
Girl. cancelorder (bakechickenwingcommand1 );
// Inform the kitchen after ordering
Girl. Policy ();
Console. readkey ();