命令模式

来源:互联网 发布:人工智能 高清百度云 编辑:程序博客网 时间:2024/05/19 02:26
建立一个接口:
1
2
3
4
5
package com;
 
public interface Command {
    void process(int[] target);
}
两个类继承这个接口:
1
2
3
4
5
6
7
8
9
10
11
package com;
 
public class PrintCommand implements Command {
    public void process(int[] target)
    {
        for(int tmp:target)
        {
            System.out.println("迭代输出数组的元素:"+tmp);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
package com;
 
public class AddCommand implements Command {
    public void process(int[] target)
    {
        int sum=0;
        for(int tmp:target)
        {
            sum+=tmp;
        }
        System.out.println("数组元素的总和是:"+sum);
    }
}
定义数组的处理类:
1
2
3
4
5
6
7
8
package com;
 
public class ProcessArray {
    public void process(int[] target,Command cmd)
    {
        cmd.process(target);
    }
}
测试程序:(传入不同的类对象,实现选择不同的处理方法)
1
2
3
4
5
6
7
8
9
10
11
package com;
 
public class CommandTest {
    public static void main(String[] args)
    {
        ProcessArray pa=new ProcessArray();
        int[] target={3,-4,6,4};
        pa.process(target, new PrintCommand());
        pa.process(target, new AddCommand());
    }
}
0 0
原创粉丝点击