①UML設計:
②定義:把命令看做一個對象,這樣就能讓命令擁有對象所有擁有的優勢
③示例:
/**
* 創建一個命令執行者
*/
public interface CommandExecutor{
void action();
}
/**
* 創建具體的命令執行者
*/
public class AttackExecutor implements CommandExecutor{
@Override
public void action(){
System.out.println("attack...");
}
}
/**
* 創建命令接收者
*/
public interface Command{
void execute();
}
/**
* 創建具體命令接收者-蹲下
*/
public class SquatCommand implements Command{
//擁有命令執行者的對象
private CommandExecutor executor;
public Squat(CommandExecutor executor){
this.executor = executor;
}
public void execute(){
System.out.println("squat...");
executor.action();
}
}
/**
* 創建具體命令接收者-移動
*/
public class MoveCommand implements Command{
//擁有命令執行者的對象
private CommandExecutor executor;
public Squat(CommandExecutor executor){
this.executor = executor;
}
public void execute(){
System.out.println("move...");
executor.action();
}
}
/**
* 創建命令指揮官
*/
public class CommandInvoker{
Command command;
public CommandInvoker(Command command){
this.command = command;
}
public void action(){
command.execute();
}
}
public class Client{
public static void main(String args[]){
CommandExecutor executor = new AttackExecutor();
Command command = new SquatCommand(executor);
CommandInvoker invoker = new CommandInvoker(command);
invoker.action();
}
}