Command模式 命令模式
行为模式之一
在面向对象的程序设计过程中,一个对象调用另一个对象,一般情况下的调用过程:创建目标对象实例,设置调用参数,调用目标对象方法
但在有些情况下,有必要使用一个专门的类对这种调用过程加以封装,我们把这种专门的类叫做Command类


Receiver
/**
* 角色:Receiver 小商贩
*/
public class PeddlerReceiver {
public void sailApple(){
System.out.println("卖苹果");
}
public void sailBanana(){
System.out.println("卖香蕉");
}
}
Command
/**
* 角色:抽象Command
*/
public abstract class Command {
private PeddlerReceiver peddler;
public Command(PeddlerReceiver peddler) {
this.peddler = peddler;
}
public PeddlerReceiver getPeddler() {
return peddler;
}
public void setPeddler(PeddlerReceiver peddler) {
this.peddler = peddler;
}
public abstract void sail();
}
/**
* 角色:ConcreteCommand
*/
public class AppleCommand extends Command{
public AppleCommand(PeddlerReceiver peddler) {
super(peddler);
}
@Override
public void sail() {
this.getPeddler().sailApple();
}
}
/**
* 角色:ConcreteCommand
*/
public class BananaCommand extends Command{
public BananaCommand(PeddlerReceiver peddler) {
super(peddler);
}
@Override
public void sail() {
this.getPeddler().sailBanana();
}
}
Invoker
/**
* 角色:Invoker 服务员
*/
public class WaiterInvoker {
private Command command;
public void sail(){
command.sail();
}
public Command getCommand() {
return command;
}
public void setCommand(Command command) {
this.command = command;
}
}
测试
/**
* 测试
*/
public class ClientTest {
public static void main(String[] args) {
PeddlerReceiver receiver = new PeddlerReceiver();
// 定义命令,并指定命令具体接收者
Command appleCommand = new AppleCommand(receiver);
Command bananaCommand = new BananaCommand(receiver);
// 定义调用者
WaiterInvoker invoker = new WaiterInvoker();
// 调用接收命令并执行
invoker.setCommand(appleCommand);
invoker.sail();
invoker.setCommand(bananaCommand);
invoker.sail();
}
}
此模式实际应用场景广泛,开发过程中或多或少都会使用到,只是不知觉是类似命令模式