场景: 需要处理一组数据,但是不知道该使用哪种处理方式,只有在处理时才知道。
其实就是想要把运行的代码作为参数传递到某个函数中去,来处理某些数据。
类似于C程序中把一个函数类型作为参数。
在java中使用接口来实现这一功能。
定义command接口
public interface Command
{
void process(int[] target);//用于封装“处理行为”
}
实现Command接口
public class AddCommand implements Command
{
public void process(int[] target)
{
int sum = 0;
for(int tmp : target)
sum += tmp;
System.out.println("sum is " + sum);
}
}
public class PrintCommand implements Command
{
public void process(int[] target)
{
for(int tmp : target)
{
System.out.println("printCommand :" + tmp);
}
}
}
处理类,处理函数有一个接口参数。
public class ProcessArray
{
public void process(int[] target, Command cmd)
{
cmd.process(target);
}
}
调用处理类
public class TestCommand
{
public static void main(String[] args)
{
int[] array = new int[] {1, 2, 3, 4, 5, 6, 7};
ProcessArray pa = new ProcessArray();
pa.process(array, new AddCommand());
pa.process(array, new PrintCommand());
}
}
5655

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



