标签:command
命令模式:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。
首先定义一个Receiver类,用来执行请求
public class Receiver {
public void action(){
System.out.println("执行请求");
}
}
接着定义Command抽象类,用来声明执行操作的接口
public abstract class Commands {
protected Receiver receiver;
public Commands(Receiver receiver){
this.receiver=receiver;
}
public abstract void execute();
}
接着定义ConcreteCommand继承Command类
public class ConcreteCommand extends Commands{
public ConcreteCommand(Receiver receiver) {
super(receiver);
}
@Override
public void execute() {
receiver.action();
}
}
然后定义Invoker类,要求该命令执行这个请求
public class Invoker {
private Commands command;
public void setCommand(Commands command){
this.command=command;
}
public void executeCommand(){
command.execute();
}
}
客户端代码
public static void main(String[] args) {
//命令模式
Receiver receiver=new Receiver();
Commands commands=new ConcreteCommand(receiver);
Invoker invoker=new Invoker();
invoker.setCommand(commands);
invoker.executeCommand();
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:command
原文地址:http://blog.csdn.net/qq_16687803/article/details/46710923