考虑这样一个需求:某个方法需要完成一个功能,完成这个功能的大部分步骤已经确定下来了,但是有少量步骤的具体实施目前无法确定下来,必须要等到执行该方法时才可以确定。这个方法不仅要求参数可变,甚至要求方法执行体中的代码可变。对于这样的要求,我们必须把方法体的处理行为作为参数传进该方法,而处理行为用编程序来实现就是一段代码块。这种需求在设计模式中就叫做“命令模式”,在Swing和GWT之中有广泛的使用(例如:事件处理使用的匿名内部类)。下面就是一个命令设计模式的实现例子:
1.
package com.lanp.command;
/**
* 处理数据数据项的借口
* @author LanP
* @version V1.0
*/
public interface MyCommand {
void process(int[] target);
}
2.
package com.lanp.command;
/**
* 处理数据数据内容的处理类
* @author LanP
* @version V1.0
*/
public class DoArray {
public void doArrayItems(int[] target,MyCommand myCmd) {
myCmd.process(target);
}
}
3.
package com.lanp.command;
/**
* 用于测试命令模式的类
* @author LanP
* @version V1.0
*/
public class TestMyCommand {
public static void main(String[] args) {
DoArray doArray = new DoArray();
int[] target = {1,-50,78,-2,9,88,520};
//第一次对数组进行处理,具体怎么样处理取决于MyCommand对象
System.out.println("----第一次对数组进行处理----");
doArray.doArrayItems(target, new MyCommand() {
@Override
public void process(int[] target) {
//遍历输出数据元素
System.out.print("数组中的元素有: ");
for(int temp : target) {
System.out.print(temp + " ");
}
System.out.println();
}
});
//第二次对数组进行处理,具体怎么样处理取决于MyCommand对象
System.out.println("----第二次对数组进行处理----");
doArray.doArrayItems(target, new MyCommand() {
//计算数组元素中的和
@Override
public void process(int[] target) {
int sum = 0;
for(int temp : target) {
sum = sum + temp;
}
System.out.println("数组中的和为: " + sum);
}
});
}
}