一、介绍
命令模式(Command),将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
二、代码实现
//接受者 public class Receiver { public void action() { System.out.println("执行请求"); } }
//抽象命令类 public abstract class Command { //接收者 protected Receiver receiver; public Command(Receiver receiver) { this.receiver = receiver; } //执行命令 public abstract void excuteCommand(); } //具体命令类 public class ConcreteCommand extends Command{ public ConcreteCommand(Receiver receiver) { super(receiver); } @Override public void excuteCommand() { receiver.action(); } } //调用方 public class Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void excuteCommand() { command.excuteCommand(); } }
测试:
public class Client { public static void main(String[] args) { //接收者 Receiver receiver = new Receiver(); //命令给接收者 Command command = new ConcreteCommand(receiver); //调用方 Invoker invoker = new Invoker(); invoker.setCommand(command); //执行命令 invoker.excuteCommand(); } }