面向接口编程——命令模式

it2024-10-16  37

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); } }

一个简单的接口设计,实现了接口的类分别有打打印数组,数组求和两个方法。 重点:在处理数组的类中,把接口作为参数传递,实现了接口的类的对象可以直接作为此参数传递

最新回复(0)