介绍:
某个方法需要完成某个行为,但这个行为无法确定,必须等到执行时才知道。
对一数组,在执行时才知道其行为。
用一接口封装处理行为,在处理类中包含一处理方法,方法无法知道处理行为,可以使用接口,这个接口参数负责处理行为,
处理行为与处理方法分离,这种模式称之为命令模式。
接口类:
package designModel;
public interface Command {
void process(int[] target);
}
处理类:
package designModel;
public class ProcessArray {
public void process(int[] target, Command cmd){
cmd.process(target);
}
}
处理方法1:
package designModel;
public class PrintCommand implements Command {
public void process(int[] target){
for(int temp : target)
System.out.println("输出的数组元素: "+ temp);
}
}
package designModel;
public class AddCommand implements Command {
public void process(int[] target){
int sum = 0;
for(int temp : target)
sum += temp;
System.out.println("数组总和为: " + sum);
}
}
运行类:
package designModel;
public class commandModel {
public static void main(String[] args){
ProcessArray pa = new ProcessArray();
int[] target = {3, -4, 6, 4};
pa.process(target, new PrintCommand());
System.out.println("--------------------");
pa.process(target, new AddCommand());
}
}
运行结果:
输出的数组元素: 3
输出的数组元素: -4
输出的数组元素: 6
输出的数组元素: 4
--------------------
数组总和为: 9