使發令者與執行者之間相分離。java
好比後臺開發過程當中的請求數據庫、RPC接口等。一般狀況下,咱們會將請求邏輯(參數封裝、結果解析、異常控制等)交給請求方控制,這樣會致使代碼邏輯十分混亂,業務邏輯與接口請求邏輯混雜在一塊兒。數據庫
Client:調用方bash
Receiver:這個無關緊要,主要作回調。獲取concreteCommand的執行結果,返回給客戶端ide
ConcreteCommand:具體命令執行者ui
Command:抽象類或者接口(通常狀況是抽象類,用於封裝通用邏輯)this
Caller:被調用的接口(一個或多個)spa
這個的代碼寫得太多了,就再也不舉了,借用wikipedia的例子吧。3d
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 void storeAndExecute(final Command cmd) {
this.history.add(cmd); // optional
cmd.execute();
}
}
/** The Receiver class */
public class Light {
public void turnOn() {
System.out.println("The light is 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(final Light light) {
this.theLight = light;
}
@Override // Command
public void execute() {
theLight.turnOn();
}
}
/** The Command for turning off the light - ConcreteCommand #2 */
public class FlipDownCommand implements Command {
private Light theLight;
public FlipDownCommand(final Light light) {
this.theLight = light;
}
@Override // Command
public void execute() {
theLight.turnOff();
}
}
/* The test class or client */
public class PressSwitch {
public static void main(final String[] arguments){
// Check number of arguments
if (arguments.length != 1) {
System.err.println("Argument \"ON\" or \"OFF\" is required.");
System.exit(-1);
}
final Light lamp = new Light();
final Command switchUp = new FlipUpCommand(lamp);
final Command switchDown = new FlipDownCommand(lamp);
final Switch mySwitch = new Switch();
switch(arguments[0]) {
case "ON":
mySwitch.storeAndExecute(switchUp);
break;
case "OFF":
mySwitch.storeAndExecute(switchDown);
break;
default:
System.err.println("Argument \"ON\" or \"OFF\" is required.");
System.exit(-1);
}
}
}
複製代碼
解釋一下,Switch至關因而原理圖Client,並無使用Receivercode
https://en.wikipedia.org/wiki/Command_patterncdn