定义:
- 将请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。
通用类图:
命令模式的通用类图
/*
* 定义一个抽象的接收类,用来定义执行命令的方法
* */
public abstract class Receiver {
public abstract void doSomething();
}
public class ReceiverOne extends Receiver {
@Override
public void doSomething() {
// TODO Auto-generated method stub
}
}
public class ReceiverTwo extends Receiver {
@Override
public void doSomething() {
// TODO Auto-generated method stub
}
}
/*
* 定义抽象的命令类
* */
public abstract class Command {
// 每个命令类都有一个执行命令的方法
public abstract void execute();
}
public class ConcreteCommandOne extends Command {
private Receiver receiver;
public ConcreteCommandOne(Receiver receiver) {
// TODO Auto-generated constructor stub
this.receiver = receiver;
}
@Override
public void execute() {
// TODO Auto-generated method stub
this.receiver.doSomething();
}
}
public class ConcreteCommandTwo extends Command {
private Receiver receiver;
public ConcreteCommandTwo(Receiver receiver) {
// TODO Auto-generated constructor stub
this.receiver = receiver;
}
@Override
public void execute() {
// TODO Auto-generated method stub
this.receiver.doSomething();
}
}
/*
* 定义执行类,根据不同的command 做出对应的操作
* */
public class Invoker {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
// 执行命令
public void action() {
this.command.execute();
}
}
public class Client {
public static void main(String[] args) {
//实际中receiver不会进行暴露,需要做好必要的封装
Invoker invoker = new Invoker();
invoker.setCommand(new ConcreteCommandOne(new ReceiverOne()));
invoker.action();
}
}
优点:
- 类间解耦:调用者和接收者之间没有任何依赖关系,调用者实现功能只需要调用Command抽象类中的execute方法
- 可拓展性:Command子类易拓展,调用者Invoker和高层次的模块Client不产生严重的代码耦合
- 结合其他模式:责任链模式,实现命令族解析任务,结合模板方法模式,可以减少Command子类的膨胀
缺点:
网友评论