java設計模式之命令模式

①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();
}
}






發佈了46 篇原創文章 · 獲贊 18 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章