初學Java,面向介面編程,命令模式(十八)

來源:互聯網
上載者:User

命令模式 :把一個請求或者操作封裝到一個對象中。命令模式把發出命令的責任和執行命令的責任分割開,委派給不同的對象。命令模式允許請求的一方和發送的一方獨立開來,使得請求的一方不必知道接收請求的一方的介面,更不必知道請求是怎麼被接收,以及操作是否執行,何時被執行以及是怎麼被執行的。系統支援命令的撤消。

命令模式就像是把“處理行為”作為參數傳入一個方法,這個“處理行為”用編程來實現就是一段代碼

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方法已經和它的處理行為分離開了,這就是請求命令一方與具體命令的解藕

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.