建立一个接口:
两个类继承这个接口:
定义数组的处理类:
测试程序:(传入不同的类对象,实现选择不同的处理方法)
|
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()); }} |
本文介绍了一种利用命令模式处理数组元素的方法。通过定义Command接口并由PrintCommand和AddCommand两个类实现,分别实现了数组元素的打印和求和功能。ProcessArray类用于执行具体命令,CommandTest类作为测试入口展示不同命令的效果。
2438

被折叠的 条评论
为什么被折叠?



