建立一个接口:
两个类继承这个接口:
定义数组的处理类:
测试程序:(传入不同的类对象,实现选择不同的处理方法)
1
2
3
4
5
|
package com; public interface Command { void process( int [] target); } |
1
2
3
4
5
6
7
8
9
10
11
|
package com; public class PrintCommand implements Command { public void process( int [] target) { for ( int tmp:target) { System.out.println( "迭代输出数组的元素:" +tmp); } } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package com; public class AddCommand implements Command { public void process( int [] target) { int sum= 0 ; for ( int tmp:target) { sum+=tmp; } System.out.println( "数组元素的总和是:" +sum); } } |
1
2
3
4
5
6
7
8
|
package com; public class ProcessArray { public void process( int [] target,Command cmd) { cmd.process(target); } } |
1
2
3
4
5
6
7
8
9
10
11
|
package com; public class CommandTest { public static void main(String[] args) { ProcessArray pa= new ProcessArray(); int [] target={ 3 ,- 4 , 6 , 4 }; pa.process(target, new PrintCommand()); pa.process(target, new AddCommand()); } } |