命令模式由三上角色构成
命令对象:将接收放注入到内部由它来构建一条命令,在内部有命令的执行的行为,
命令的接收方:负责接收外部的命令
请求命令,命令的发送方:将构建成功的命令对象注入,可执行不同的命令。在内部有请求执行命令的行为
下面是一个小例子:
package com.lovo.test;
public abstract class Command {
protected Receiverable receiver;
public Command(Receiverable receiver) {
this.receiver = receiver;
}
public abstract void execute();
}
package com.lovo.test;
public class CommandImpl extends Command {
public CommandImpl(Receiverable receiver) {
super(receiver);
}
public void execute() {
receiver.receive();
}
}
package com.lovo.test;
public interface Receiverable {
public void receive();
}
package com.lovo.test;
public class Receiver implements Receiverable {
@Override
public void receive() {
System.out.println("This is Receive class!");
}
}
package com.lovo.test;
public class Invoker {
private Command command;
// 使用set注入
public void setCommand(Command command) {
this.command = command;
}
public void execute() {
command.execute();
}
}
package com.lovo.test;
public class OpenGun implements Receiverable {
@Override
public void receive() {
// TODO Auto-generated method stub
System.out.println("向敌人开火");
}
}
package com.lovo.test;
public class Test {
public static void main(String[] args) {
Receiver rec = new Receiver();
OpenGun og = new OpenGun(); // 命令的接收方,负责将接收到命令
GoJapan gj = new GoJapan();
Command cmd = new CommandImpl(gj); // 将命令的接收方传入命令对象中,构建一条命令
Invoker i = new Invoker(); // 请求执行此命令,请求的发出方
i.setCommand(cmd);
i.execute(); // 执行命令
}
}
转载于:https://blog.51cto.com/mrwlh/1091046