将一个请求封装为一个对象,使发出请求的责任和执行请求的责任分割开。这样两者之间通过命令对象进行沟通,这样方便将命令对象进行储存、传递、调用、增加与管理
“行为请求者” 与 “行为实现者” 通常呈现一种“紧耦合”。但在某些场合,比如要对行为进行“记录、撤销/重做、事务”等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,如何将“行为请求者”与“行为实现者”解耦?将一组行为抽象为对象,实现二者之间的松耦合。这就是命令模式(Command Pattern)要解决的问题
手机和电脑均支持开关机,而开机和关机就是两个命令;手机和电脑就是两个接收者;很多时候我们只需要知道如何发送请求,即我要发送关机的命令。但我不关心他如何关机

Command
- package com.behaviour.command.Command;
-
- /**
- * Command ===> 命令角色
- * 该命令支持 开机和关机
- */
- public interface Command {
-
- public abstract void powerOn();
- public abstract void powerOff();
- }
ConcreteCommand
- package com.behaviour.command.ConcreteCommand;
-
- import com.behaviour.command.Command.Command;
- import com.behaviour.command.Receiver.Receiver;
-
- /**
- * ConcreteCommand ===> 命令的实现者
- * 内部持有接收者Receiver对象(当前命令的执行者),将一个接受者对象与一个动作绑定
- */
- public class ConcreteCommand implements Command {
-
- private Receiver receiver;
-
- public ConcreteCommand(Receiver receiver) {
- this.receiver = receiver;
- }
-
- @Override
- public void powerOn() {
- receiver.on();
- }
-
- @Override
- public void powerOff() {
- receiver.off();
- }
- }
Receiver
- package com.behaviour.command.Receiver;
-
- /**
- * 接收者角色,真正执行命令的对象 Receiver
- * 可以是一个类,也可以是一个接口或抽象类;这里写成接口主要是为了方便通用,因为不同的客户端可能支持同样的命令;例如手机和电脑都支持开关机
- */
- public interface Receiver {
- public abstract void on();
- public abstract void off();
- }
PCComputerReceiver
- package com.behaviour.command.Receiver;
-
- /**
- * 接收者角色 Receiver 的具体实现类
- */
- public class PCComputerReceiver implements Receiver{
-
- @Override
- public void on() {
- System.out.println("电脑开机了");
- }
-
- @Override
- public void off() {
- System.out.println("电脑关机了");
- }
- }
MobileReceiver
- package com.behaviour.command.Receiver;
-
- /**
- * 接收者角色 Receiver 的具体实现类
- */
- public class MobileReceiver implements Receiver{
-
- @Override
- public void on() {
- System.out.println("手机开机了");
- }
-
- @Override
- public void off() {
- System.out.println("手机关机了");
- }
- }
Invoker
- package com.behaviour.command.Invoker;
-
- import com.behaviour.command.Command.Command;
-
- /**
- * 命令调用者角色 Invoker
- * 要求命令对象执行请求
- */
- public class Invoker {
-
- private Command command;
-
- public Invoker(Command command){
- this.command = command;
- }
-
- public void powerOn(){
- this.command.powerOn();
- }
-
- public void powerOff(){
- this.command.powerOff();
- }
- }
Test
- package com.behaviour.command;
-
- import com.behaviour.command.ConcreteCommand.ConcreteCommand;
- import com.behaviour.command.Invoker.Invoker;
- import com.behaviour.command.Receiver.MobileReceiver;
-
- public class Test {
-
- public static void main(String[] args) {
-
- Invoker invoker = new Invoker(new ConcreteCommand(new MobileReceiver()));
- invoker.powerOn();
- invoker.powerOff();
- }
- }