Command mode. In. net, the Java platform uses a lot of event mechanisms and deals with them almost every day.
What impressed me most in Android is the multi-threaded Multi-process environment. Therefore, runbable and thread must be used in a large amount. In fact, the simplest command mode is used.
Command mode, Command pattern, how clever it is to encapsulate a request into an object.
1. Intention
Encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests or record request logs, and support auditable operations.
Popular Words:Action thing request encapsulation queuing and packaging Asynchronization
2. Structure
The command interface provides the execute method. The client calls the recriver by calling the command operation through invoker, but encapsulates the specific operation request to the hacker in a specific command, it is a clear and concise client operation on recriver.
However, in actual projects, we often ignore aggreger, and directly set the target object of the command object to its own member variable of the subclass or as a temporary variable of the execute () method.
Take runnable in Android (under the java. lang Package) as an example. The UML structure is shown below:
Unexpectedly, the code we write every day is unconsciously using the command mode. The so-called mode is omnipresent.
3.Code
The runnable command interface is defined as follows:
Public interface runnable {public abstract void run ();}
Caller thread simplified code:
// The command mode does not need to inherit the runnable interface. However, considering the actual situation, such as convenience, the runnable interface is inherited and the run method is implemented, this is the run method of the thread itself. Class thread implements runnable {private runnable target; Public thread (runnable target) {this.tar get = target;} public synchronized void start () {If (threadstatus! = 0 | this! = Me) throw new illegalthreadstateexception (); group. add (this); start0 (); // This is a local method. Call the run method if (stopbeforestart) {stop0 (throwablefromstop) ;}// optional public void run () {If (target! = NULL) {target. Run ();}}}
The client only needs new thread (New runnable () {}). Start () to start executing a series of related requests. Most of these requests are anonymous classes that implement the runnable interface.
4. Results
(1). behavior model;
(2). decouple the operation of the called object and the object that knows how to implement the operation;
(3) Multiple commands can be assembled into a composite command;
(4). It is easy to add new commands.