- // An interface for an array to command
- interface Command
- {
- public abstract void command(int[] targetArray);
- }
- //the two implements of the Command Interface
- class PrintArrays implements Command
- {
- public void command(int[] targetArray)
- {
- System.out.println("The content of the array is:");
-
- for(int index:targetArray)
- System.out.print(""+index+'\t');
-
- System.out.println("");
-
- System.out.println("print is over!");
- }
- }
- class IteratorArrays implements Command
- {
- public void command(int[] targetArray)
- {
- int result = 0;
- System.out.println("Now it\'s time to get the result.");
-
- for(int index:targetArray)
- result+=index;
-
- System.out.println("the sum of the array is:"+ result);
- }
- }
- class ArrayProcess
- {
- public void process(int[] targetArray,Command cmd)//定义一个Command类型的变量,负责对数组的处理行为
- {
- cmd.command(targetArray);
- }
- }
- public class myCommandMode
- {
- public static void main(String[] args)
- {
- int[] array={-1,2,-3,4,5};
- ArrayProcess ap = new ArrayProcess();
-
- /*
- PrintArrays pa = new PrintArrays();
- IteratorArrays ia = new IteratorArrays();
-
-
- pa.command(array);
- ia.command(array);
- */
-
- ap.process(array,new PrintArrays());//the usage of Inner class
-
- ap.process(array,new IteratorArrays());//the usage of Inner class
- }
- }
复制代码 |
|