package Day05
;
public class TestCommand {
public static void main(String
[] args
) {
ProcessArrayCommand pc
= new ProcessArrayCommand();
int[] a
={1,2,3,4,5,6,7,78};
Command pr
= new PrintArray();
Command sa
= new SumArray();
pc
.processarray(a
,pr
);
System
.out
.println("-----------");
pc
.processarray(a
,sa
);
}
}
interface Command{
public void processarray(int[] src
);
}
class PrintArray implements Command{
@Override
public void processarray(int[] src
) {
for (int temp
:src
)
{
System
.out
.println(temp
);
}
}
}
class SumArray implements Command{
int sum
=0;
@Override
public void processarray(int[] src
) {
for (int temp
:src
)
{
sum
+=temp
;
}
System
.out
.println("数组的和:"+sum
);
}
}
class ProcessArrayCommand{
public void processarray(int[] src
,Command cmd
){
cmd
.processarray(src
);
}
}
一个简单的接口设计,实现了接口的类分别有打打印数组,数组求和两个方法。 重点:在处理数组的类中,把接口作为参数传递,实现了接口的类的对象可以直接作为此参数传递
转载请注明原文地址: https://lol.8miu.com/read-19376.html