Command pattern in Java)

Source: Internet
Author: User

1. Concept

Pass requests from the client into an object so that you can parameterize the customer with different requests. This function is used to decouple "behavior requestor" from "behavior implementer" to achieve loose coupling between the two to adapt to changes. Separate the changing and changing factors.

In the object-orientedProgramIn the design, an object calls another object. Generally, the call process is: Create a target object instance, set the call parameters, and call the method of the target object.

However, in some cases, it is necessary to use a special class to encapsulate this call process. We call this special class the command class.

Command mode can be applied
A) The entire call process is complicated, or there are multiple such calls. In this case, the command class is used to encapsulate the call to facilitate reuse of functions.
B) The call parameters must be processed before and after the call.
C) some additional processing is required before and after the call, such as logs, caches, and history operations.

The command mode has the following effects:
A) decouple the object that calls the operation and the object that knows how to implement the operation.
B) command is the first-class object. They can be operated and expanded like other objects.
C) You can assemble multiple commands into one conforming command.
D) It is easy to add a new command because it does not need to change the existing class.

 

2. UML

3.Code

 Public   Interface Command {
Public Void Execute ();
}


Public Class Concretecommand Implements Command {

Private Extends er extends ER = Null ;
Private String state;

Public Concretecommand (extends er extends ER ){
This . Cycler = Cycler;
}
Public Void Execute (){
Aggreger. Action ();
}
}


Public Class Explorer {
Public Void Action (){
// Code for executing commands
}
}


Public Class Invoker {
Private Command command = Null ;

Public Void Setcommand (command ){
This . Command = command;
}

Public Void Runcommand (){
Command.exe cute ();
}
}

Public Class Client {
Public Void Assemble (){
// Create Receiver
Extends er extends ER = New Aggreger ();
// Create a command object and set its Receiver
Command command = New Concretecommand (aggreger );
// Create invoker and set the command object
Invoker = New Invoker ();
Invoker. setcommand (command );
}
}
The following example describes how to simulate operations on a TV set, such as starting, shutting down, and changing the TV set. The Code is as follows:

// Command recipient
Public Class TV {
Public Int Currentchannel = 0;

Public Void Turnon (){
System. Out. println ("The televisino is on .");
}

Public Void Turnoff (){
System. Out. println ("the television is off .");
}

Public Void Changechannel ( Int Channel ){
This . Currentchannel = channel;
System. Out. println ("Now TV channel is" + channel );
}
}

// Command Execution Interface
Public Interface Command {
Void Execute ();
}

// Boot command
Public Class CommandonImplements Command {
Private TV mytv;

Public Commandon (TV ){
Mytv = TV;
}

Public Void Execute (){
Mytv. turnon ();
}
}

// Shutdown command
Public Class Commandoff Implements Command {
Private TV mytv;

Public Commandoff (TV ){
Mytv = TV;
}

Public Void Execute (){
Mytv. turnoff ();
}
}

// Channel switching command
Public Class Commandchange Implements Command {
Private TV mytv;

Private Int Channel;

Public Commandchange (TV, Int Channel ){
Mytv = TV;
This . Channel = channel;
}

Public Void Execute (){
Mytv. changechannel (Channel );
}
}

// It can be seen as a remote control.
Public Class Control {
Private Command oncommand, offcommand, changechannel;

Public Control (command on, command off, Command Channel ){
Oncommand = on;
Offcommand = off;
Changechannel = channel;
}

Public Void Turnon (){
Oncommand.exe cute ();
}

Public Void Turnoff (){
Offcommand.exe cute ();
}

Public Void Changechannel (){
Changechannel.exe cute ();
}
}

// Test class
Public Class Client {
Public Static Void Main (string [] ARGs ){
// Command recipient
TV mytv = New TV ();
// Boot command
Commandon = New Commandon (mytv );
// Shutdown command
Commandoff off = New Commandoff (mytv );
// Channel switching command
Commandchange channel = New Commandchange (mytv, 2 );
// Command Control Object
Control control = New Control (On, off, Channel );

// Start
Control. turnon ();
// Switch channels
Control. changechannel ();
// Shutdown
Control. turnoff ();
}
}


The execution result is:
The televisino is on.
Now TV channel is 2
The television is off.

4. Application scenarios

The command mode should be considered in the following situations:

1) Use the command mode as an alternative to "Callback" in the object-oriented system. "Callback" refers to registering a function and then calling it later.

2) You must specify the request at different times and queue the request. A command object and the original request sender can have different lifecycles. In other words, the original request sender may no longer exist, and the command object itself is still active. At this time, the command receiver can be local or another address on the network. The command object can be transmitted to another machine after being serialized.

3) The system must support undo commands ). The command object can store the status. When the client needs to revoke the effect of the command, it can call the Undo () method to cancel the effect of the command. The command object can also provide the Redo () method for the client to re-execute the command when needed.

4) if a system wants to update all the data in the system to the log, so that when the system crashes, it can read all the data update commands in the log and re-call execute () to restore the data updates made by the system before the crash.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.