命令模式 :把一個請求或者操作封裝到一個對象中。命令模式把發出命令的責任和執行命令的責任分割開,委派給不同的對象。命令模式允許請求的一方和發送的一方獨立開來,使得請求的一方不必知道接收請求的一方的介面,更不必知道請求是怎麼被接收,以及操作是否執行,何時被執行以及是怎麼被執行的。系統支援命令的撤消。
命令模式就像是把“處理行為”作為參數傳入一個方法,這個“處理行為”用編程來實現就是一段代碼
public interface Command{//介面裡定義的process方法用於封裝"處理行為"void process(int[] target);}
public class ProcessArray {public void process(int[] target,Command cmd){cmd.process(target);}}
public class PrintCommand implements Command {public void process(int[] target){for(int tmp : target){System.out.println("迭代輸出目標數組的元素:" + tmp);}}}
public class AddCommand implements Command {public void process(int[] target){int sum = 0;for(int tmp : target){sum += tmp;}System.out.println("數組元素的總和是:" + sum);}}
public class TestCommand {public static void main(String[] args) {ProcessArray pa = new ProcessArray();int[] target = {3,-4,6,4};//第一次處理數組,具體處理行為取決於PrintCommandpa.process(target,new PrintCommand());//第二次處理數組,具體處理行為取決於AddCommandpa.process(target,new AddCommand());}}
TestCommand為請求命令的一方,它只關心process方法,至於執行process方法的時候,具體做的什麼操作,由傳入的參數決定
process方法已經和它的處理行為分離開了,這就是請求命令一方與具體命令的解藕