將一個請求封裝成一個對象,從而能夠使用不一樣的請求來參數化客戶端。java
命令模式一般有3種角色ide
Receiver:接收者角色。負責執行命令的角色this
抽象接收者:具備全部特性的接收者的集合code
public abstract class AbstractReceiver { public abstract void action(); }
具體接收者角色:執行不一樣的業務邏輯對象
public class ReceiverOne extends AbstractReceiver { @Override public void action() { System.out.println("執行ReceiverOne的業務邏輯"); } } public class ReceiverTwo extends AbstractReceiver { @Override public void action() { System.out.println("執行ReceiverTwo的業務邏輯"); } }
Command:命令角色。須要執行的命令,指定接收者來執行命令io
抽象命令:指定命令接收者,並執行命令class
public abstract class AbstractCommand { /** * 定義一個子類的共享變量(命令接收者) */ protected final AbstractReceiver receiver; /** * 指定命令接收者 * @param receiver */ public AbstractCommand(AbstractReceiver receiver) { this.receiver = receiver; } /** * 執行命令 */ public abstract void execute(); }
具體命令:每個命令是對一個或多個接收者的封裝,採用封閉Receiver方式,能夠減少上層模塊對下層模塊的依賴變量
public class CommandOne extends AbstractCommand { /** * 指定命令接收者 * @param receiver */ public CommandOne(AbstractReceiver receiver) { super(receiver); } @Override public void execute() { super.receiver.action(); } } public class CommandTwo extends AbstractCommand { /** * 指定命令接收者 * @param receiver */ public CommandTwo(AbstractReceiver receiver) { super(receiver); } @Override public void execute() { super.receiver.action(); } }
Invoker:調用者角色。接收命令並執行擴展
public class Invoker { private AbstractCommand command; /** * 接收命令 * @param command */ public void setCommand(AbstractCommand command) { this.command = command; } /** * 執行命令 */ public void run() { this.command.execute(); } }
場景類請求
public class Client { public static void main(String[] args) { // 聲明調用者 Invoker invoker = new Invoker(); // 定義一個發送給接收者的命令 AbstractCommand commandOne = new CommandOne(); // 調用者執行命令 invoker.setCommand(commandOne); invoker.run(); AbstractReceiver receiver = new ReceiverTwo(); AbstractCommand commandTwo = new CommandTwo(receiver); invoker.setCommand(commandTwo); invoker.run(); } }
觸發-反饋機制的處理
備忘錄模式見後續博文
修改接收者角色,新增rollBack
方法,回滾任務
public abstract class AbstractReceiver { public abstract void action(); public abstract void rollBack(); } public class ReceiverOne extends AbstractReceiver { @Override public void action() { System.out.println("執行ReceiverOne的業務邏輯"); } @Override public void rollBack() { System.out.println("撤銷ReceiverOne的action操做"); } }
新增撤銷命令
public class RollBackOneCommand extends AbstractCommand { /** * 指定一個默認命令接收者 */ public RollBackOneCommand() { super(new ReceiverOne()); } /** * 指定命令接收者 * @param receiver */ public RollBackOneCommand(AbstractReceiver receiver) { super(receiver); } @Override public void execute() { super.receiver.rollBack(); } }