Command pattern: Encapsulates a request as an object, allowing us to parameterize the client with different requests, queue requests or log requests, and support revocable operations. The command pattern is an object-oriented pattern with an alias of Action (action) mode or transaction (Transaction) mode.
The command pattern contains the following roles:
- Command: Abstract Commands class
- Concretecommand: Specific Command class
- Invoker: Caller
- Receiver: Receiver
- Client: Customer Class
Code
Import java.util.list;import java.util.arraylist;/* The Command interface */public interface command {void execute ();} /* The Invoker class */public class Switch {private list<command> history = new arraylist<command> (); Public Switch () {} public void Storeandexecute (Command cmd) {this.history.add (cmd);//optional CMD.EXECU Te (); }}/* the Receiver class */public class light {public light () {} public void TurnOn () {System.out.println ("Th E light was on "); } public void Turnoff () {System.out.println ("The Light is Off"); }}/* the command for turning on the Light-concretecommand #1 */public class Flipupcommand implements Command {private Light thelight; Public Flipupcommand (light) {this.thelight = light; } public void Execute () {Thelight.turnon (); }}/* the command for turning off the Light-concretecommand #2 */public class Flipdowncommand implements Command {Priv Ate light thelight; PuBlic Flipdowncommand (Light light) {this.thelight = light; } public void Execute () {Thelight.turnoff (); }}/* the test class or client */public class Pressswitch {public static void main (string[] args) {Light lamp = new Light (); Command switchup = new Flipupcommand (lamp); Command Switchdown = new Flipdowncommand (lamp); Switch myswitch = new switch (); try {if ("on". Equalsignorecase (Args[0])) {Myswitch.storeandexecute (switchup); } else if ("OFF". Equalsignorecase (Args[0])) {Myswitch.storeandexecute (Switchdown); } else {System.out.println ("Argument \" on\ "or \" off\ "is required.");}} catch (Exception e) {System.out.println ("Arguments required."); } }}
Advantages of the Command mode
- Reduce the coupling degree of the system.
- New commands can be easily added to the system.
- It is easier to design a command queue and a macro command (combined command).
- The undo and redo of the request can be easily implemented.
Disadvantages of the command pattern
- Using command mode may cause some systems to have too many specific command classes. Because you need to design a specific command class for each command, some systems may require a large number of specific command classes, which will affect the use of the command pattern.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Command mode