解決問題
使發(fā)令者與執(zhí)行者之間相分離狰域。
應(yīng)用場(chǎng)景
比如后臺(tái)開發(fā)過程中的請(qǐng)求數(shù)據(jù)庫、RPC接口等谷炸。通常情況下,我們會(huì)將請(qǐng)求邏輯(參數(shù)封裝禀挫、結(jié)果解析旬陡、異常控制等)交給請(qǐng)求方控制语婴,這樣會(huì)導(dǎo)致代碼邏輯十分混亂描孟,業(yè)務(wù)邏輯與接口請(qǐng)求邏輯混雜在一起。
原理圖
image
Client:調(diào)用方
Receiver:這個(gè)可有可無砰左,主要做回調(diào)匿醒。獲取concreteCommand的執(zhí)行結(jié)果,返回給客戶端
ConcreteCommand:具體命令執(zhí)行者
Command:抽象類或者接口(一般情況是抽象類缠导,用于封裝通用邏輯)
Caller:被調(diào)用的接口(一個(gè)或多個(gè))
示例
這個(gè)的代碼寫得太多了廉羔,就不再舉了,借用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相當(dāng)于是原理圖Client,并沒有使用Receiver