【設計模式】【命令模式】
/** * Description: * <br/>網站: <a href="https://www.crazyit.org">瘋狂Java聯盟</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class ProcessArray { //定義一個each()方法,用於處理數組, public void each(int[] target , Command cmd) { cmd.process(target); } }
/** * Description: * <br/>網站: <a href="https://www.crazyit.org">瘋狂Java聯盟</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public interface Command { //接口裏定義的process方法用於封裝“處理行為” void process(int[] target); }
/** * Description: * <br/>網站: <a href="https://www.crazyit.org">瘋狂Java聯盟</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class CommandTest { public static void main(String[] args) { ProcessArray pa = new ProcessArray(); int[] target = {3, -4, 6, 4}; //第一次處理數組,具體處理行為取決於Command對象 pa.each(target , new Command() { //重寫process()方法,決定具體的處理行為 public void process(int[] target) { for (int tmp : target ) { System.out.println("迭代輸出目標數組的元素:" + tmp); } } }); System.out.println("------------------"); //第二次處理數組,具體處理行為取決於Command對象 pa.each(target , new Command() { //重寫process方法,決定具體的處理行為 public void process(int[] target) { int sum = 0; for (int tmp : target ) { sum += tmp; } System.out.println("數組元素的總和是:" + sum); } }); } }
最後更新:2017-04-04 07:03:38