java设计模式(三):command(命令模式)

来源:互联网 发布:华为商城抢购软件 编辑:程序博客网 时间:2024/06/16 13:03

        有时候我们会遇到这样一种场景:某个方法需要完成一个行为,但这个行为需要等到执行该方法的时候才能确定。具体来说,要对一个数组进行某个操作,但无法确定具体的操作,这时,可以定义一个方法ProcessArray,该方法具有两个参数,一个是要操作的数组,一个是具体的操作,由于这个操作不明确,可以定义一个接口command,里面有方法proces,需要实现的每一个操作都可以实现这个接口里的process方法。

public class ProcessArray {public void processArray(int[] target,Command cmd){cmd.process(target);}}


 

public interface Command {void process(int[] target);}


 

public class AddCommand implements Command{public void process(int[] target){int sum = 0;for(int i : target){sum += i;}System.out.println("数组元素的和为 :" + sum);}}


 

public class PrintCommand implements Command{public void process(int[] target){for(int i : target){System.out.println("输出目标数组元素 : " + i);}}}


 

public class Main {public static void main(String[] args){ProcessArray pa = new ProcessArray();int[] target = {2,5,8,4};pa.processArray(target, new PrintCommand());pa.processArray(target, new AddCommand());}}