1. //命令模式  
  2. interface Command  
  3. {  
  4.     //接口里定义的process方法用于封装“处理行为”  
  5.     void process(int[] target);   
  6. }  
  7. class ProcessArray  
  8. {  
  9.     public void process(int[] target,Command cmd)  
  10.     {  
  11.         cmd.process(target);      
  12.     }     
  13. }  
  14. class PrintCommand implements Command  
  15. {  
  16.     public void process(int[] target)  
  17.     {  
  18.         for(int tmp :target)  
  19.         {  
  20.             System.out.println("迭代输出目标数组的元素:"+tmp);   
  21.         }     
  22.     }     
  23. }  
  24. class AddCommand implements Command  
  25. {  
  26.     public void process(int[] target)  
  27.     {  
  28.         int sum = 0;  
  29.         for(int tmp : target)  
  30.         {  
  31.             sum += tmp;   
  32.         }     
  33.         System.out.println("数组元素的总和是:"+sum);  
  34.     }     
  35. }  
  36.  
  37. public class TestCommand  
  38. {  
  39.     public static void main(String[] args)  
  40.     {  
  41.         ProcessArray pa = new ProcessArray();  
  42.         int[] target = {3,-4,6,4};  
  43.         //第一次处理数组,具体处理行为取决于PrintCommand  
  44.         pa.process(target,new PrintCommand());  
  45.         System.out.println("---------------------");  
  46.         //第二次处理数组,具体处理行为取决于AddCommand  
  47.         pa.process(target,new AddCommand());  
  48. ;   }     
  49. }  
  50. //实现process方法和“处理行为”的分离