A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© a80C51 中级黑马   /  2015-9-7 10:18  /  315 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. // An interface for an array to command
  2. interface Command
  3. {
  4.         public abstract void command(int[] targetArray);
  5. }

  6. //the two implements of the Command Interface
  7. class PrintArrays implements Command
  8. {
  9.         public void command(int[] targetArray)
  10.         {
  11.                 System.out.println("The content of the array is:");
  12.                
  13.                 for(int index:targetArray)
  14.                         System.out.print(""+index+'\t');
  15.                        
  16.                 System.out.println("");
  17.                        
  18.                 System.out.println("print is over!");
  19.         }
  20. }

  21. class IteratorArrays implements Command
  22. {
  23.         public void command(int[] targetArray)
  24.         {
  25.                 int result = 0;
  26.                 System.out.println("Now it\'s time to get the result.");
  27.                
  28.                 for(int index:targetArray)
  29.                         result+=index;
  30.                
  31.                 System.out.println("the sum of the array is:"+ result);               
  32.         }
  33. }

  34. class ArrayProcess
  35. {
  36.         public void process(int[] targetArray,Command cmd)//定义一个Command类型的变量,负责对数组的处理行为
  37.         {
  38.                 cmd.command(targetArray);
  39.         }
  40. }

  41. public class myCommandMode
  42. {
  43.         public static void main(String[] args)
  44.         {
  45.                 int[] array={-1,2,-3,4,5};
  46.                 ArrayProcess ap = new ArrayProcess();
  47.                
  48.                 /*
  49.                 PrintArrays pa = new PrintArrays();
  50.                 IteratorArrays ia = new IteratorArrays();
  51.                
  52.                
  53.                 pa.command(array);
  54.                 ia.command(array);
  55.                 */
  56.                
  57.                 ap.process(array,new PrintArrays());//the usage of Inner class
  58.                
  59.                 ap.process(array,new IteratorArrays());//the usage of Inner class

  60.         }
  61. }
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马