黑马程序员技术交流社区
标题:
接口的使用实例之命令模式
[打印本页]
作者:
a80C51
时间:
2015-9-7 10:18
标题:
接口的使用实例之命令模式
// An interface for an array to command
interface Command
{
public abstract void command(int[] targetArray);
}
//the two implements of the Command Interface
class PrintArrays implements Command
{
public void command(int[] targetArray)
{
System.out.println("The content of the array is:");
for(int index:targetArray)
System.out.print(""+index+'\t');
System.out.println("");
System.out.println("print is over!");
}
}
class IteratorArrays implements Command
{
public void command(int[] targetArray)
{
int result = 0;
System.out.println("Now it\'s time to get the result.");
for(int index:targetArray)
result+=index;
System.out.println("the sum of the array is:"+ result);
}
}
class ArrayProcess
{
public void process(int[] targetArray,Command cmd)//定义一个Command类型的变量,负责对数组的处理行为
{
cmd.command(targetArray);
}
}
public class myCommandMode
{
public static void main(String[] args)
{
int[] array={-1,2,-3,4,5};
ArrayProcess ap = new ArrayProcess();
/*
PrintArrays pa = new PrintArrays();
IteratorArrays ia = new IteratorArrays();
pa.command(array);
ia.command(array);
*/
ap.process(array,new PrintArrays());//the usage of Inner class
ap.process(array,new IteratorArrays());//the usage of Inner class
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2