解決問題
使發令者與執行者之間相分離。
應用場景
比如後臺開發過程中的請求資料庫、RPC介面等。通常情況下,我們會將請求邏輯(引數封裝、結果解析、異常控制等)交給請求方控制,這樣會導致程式碼邏輯十分混亂,業務邏輯與介面請求邏輯混雜在一起。
原理圖
-
Client:呼叫方
-
Receiver:這個可有可無,主要做回撥。獲取concreteCommand的執行結果,返回給客戶端
-
ConcreteCommand:具體命令執行者
-
Command:抽象類或者介面(一般情況是抽象類,用於封裝通用邏輯)
-
Caller:被呼叫的介面(一個或多個)
示例
這個的程式碼寫得太多了,就不再舉了,借用wikipedia的例子吧。
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,並沒有使用Receiver
參考
https://en.wikipedia.org/wiki/Command_pattern