命令模式(1)
命令模式的四种角色:
1、接受者(Receiver)负责执行请求的相关操作的一个类
2、命令接口:(Command)用于封装请求的方法
3、具体命令:(ConcreteCommand)命令接口的具体实现类
4、请求者:(Invoker)包含了命令接口的实例变量,负责调用具体命令
请求者: package DesignPatterns.CommandMode; public class Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void startCommand(){ command.execute(); } }
命令接口: package DesignPatterns.CommandMode; public interface Command { public void execute(); }
具体命令:
package DesignPatterns.CommandMode;
public class ConcreteCommand implements Command{
private Receiver receiver;
public ConcreteCommand(Receiver receiver)
{
this.receiver=receiver;
}
public void execute()
{
receiver.printCommand();
}
}
接受者:
package DesignPatterns.CommandMode;
public class Receiver {
public void printCommand()
{
System.out.println("执行命令");
}
}
测试类:
package DesignPatterns.CommandMode;
public class Application {
public static void main(String[] args)
{
Receiver receiver=new Receiver();
Command command=new ConcreteCommand(receiver);
Invoker invoker=new Invoker();
invoker.setCommand(command);
invoker.startCommand();
}
}