一、UML类图
二、代码示例
public class Client {
public static void main ( String [ ] args) {
Command command = new ConcreteCommand ( new Receiver ( ) ) ;
Invoker invoker = new Invoker ( command) ;
invoker. call ( ) ;
}
}
public interface Command {
void execute ( ) ;
}
public class ConcreteCommand implements Command {
private Receiver receiver = null ;
public ConcreteCommand ( Receiver receiver) {
this . receiver = receiver;
}
@Override
public void execute ( ) {
this . receiver. action ( ) ;
}
}
public class Receiver {
public void action ( ) { }
}
public class Invoker {
private Command command;
public Invoker ( Command command) {
this . command = command;
}
public void call ( ) {
this . command. execute ( ) ;
}
}
三、角色介绍
Client(客户端): 客户端角色,程序的调用者。Command(命令): 负责定义命令的接口。ConcreteCommand(具体的命令): 负责实现在Command角色中定义的接口。Receiver(接收者): 该角色是Command角色执行命令时的对象,即命令的接收者。Invoker(发动者): 该角色是开始执行命令的角色,调用在Command角色中定义的接口。