1.定义
命令行模式是一种高内聚的模式,将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。
2.UML
3.代码
public abstract class Receiver {
abstract void doSomething();
}
public class ConcreteReceiver1 extends Receiver {
@Override
void doSomething() {
}
}
public class ConcreteReceiver2 extends Receiver {
@Override
void doSomething() {
}
}
public abstract class Command {
protected Receiver mReceiver;
abstract void execute();
public Command(Receiver receiver) {
mReceiver = receiver;
}
}
public class ConcreteCommand1 extends Command {
public ConcreteCommand1() {
super(new ConcreteReceiver1());
}
@Override
void execute() {
mReceiver.doSomething();
}
}
public class ConcreteCommand2 extends Command {
public ConcreteCommand2() {
super(new ConcreteReceiver2());
}
@Override
void execute() {
mReceiver.doSomething();
}
}
public class Client {
public static void main(String[] args) {
Command command1 = new ConcreteCommand1();
command1.execute();
Command command2 = new ConcreteCommand2();
command2.execute();
}
}