public interface Command
{
//接口里定义process方法用于封装“处理行为”
void process(int [] target);
}
处理数组的处理类ProcessArray
public class ProcessArray
{
public void procsess(int[] target ,Command cmd)
{
cmd.process(target);
}
}
Command接口的两个实现类
public class AddCommand implements Command
{
@Override
public void process(int[] target)
{
int sum =0;
for(int tmp:target)
{
sum+=tmp;
}
System.out.println("数组元素的总和是:”+sum);
}
}
public class PrintCommand implements Command
{
@Override
public void process(int[] target)
{
for(int tmp:target)
{
System.out.println("迭代输出数组元素:"+tmp);
}
}
}
CommandTest
public class CommandTest
{
public static void main(String[]args)
{
ProcessArray pa = new ProcessArray ;
int [] target = {1,3,5,7,9};
//第一次处理数组,具体处理行为取决于PrintCommand
pa.process( target , new PrintCommand());
//第一次处理数组,具体处理行为取决于AddCommand
pa.process( target , new AddCommand());
}
}