zoukankan      html  css  js  c++  java
  • 设计模式-命令模式

    命令模式

    某个方法要完成某个功能,完成这个功能的大部分步骤已经确定了,但是有少量步骤无法确定,必须等到执行方法时才能确定

     

    第一步,创建接口

    package study.command;

     

    /**

     * 命令类的接口

     * @author rocky

     *

     */

    public interface Command

    {

        /**

         * 可以给多个实现类使用的方法

         * @param array

         */

        void process(int[] array);

    }

     

    第二步 实现接口并实现方法

    import study.command.Command;

    /**

     * 实现Command类,具有打印的功能

     * @author rocky

     *

     */

    public class PrintCommand implements Command

    {

     

        @Override

        public void process(int[] array)

        {

            for(int i : array)

            {

                System.out.println(i);

            }

        }

    }

    package study.commandImpl;

     

    import study.command.Command;

    /**

     * 实现求和功能的接口

     * @author rocky

     *

     */

    public class SumCommand implements Command

    {

        @Override

        public void process(int[] array)

        {

            int sum = 0;

            for(int i : array)

            {

                sum += i;   

            }

            System.out.println(sum);

        }

     

    }

    第三步,使用命令模式

    package study.commandTest;

     

    import study.command.Command;

    import study.commandImpl.PrintCommand;

    import study.commandImpl.SumCommand;

    /**

     * 测试命令模式的类

     * @author rocky

     *

     */

    public class TstCommand

    {

        /**

         * 

         * @param array 测试的数组

         * @param command 命令类的实现类,根据需求传入对应的实现类

         */

        public void test (int[] array, Command command)

        {

            command.process(array);

        }

        public static void main(String[] args)

        {

            Command printCommand = new PrintCommand();

            Command sumCommand = new SumCommand();

            int[] array = new int[]{1,1,1,1};

            //new TstCommand().test(array, printCommand);

            new TstCommand().test(array, sumCommand);

        }

    }

     

     

  • 相关阅读:
    nyoj 599-奋斗的小蜗牛 (double ceil(); (temp
    nyoj 596-谁是最好的Coder (greater, less)
    nyoj 517-最小公倍数 (python range(start, end) range(length))
    用深度学习预测专业棋手走法
    阿里AI设计师一秒出图,小撒连连惊呼,真相是...
    想成为数据科学家?先做到这6点吧!
    Kubernetes 弹性伸缩全场景解析 (一)- 概念延伸与组件布局
    机器学习基础:(Python)训练集测试集分割与交叉验证
    Data Lake Analytics + OSS数据文件格式处理大全
    聊聊Flexbox布局中的flex的演算法
  • 原文地址:https://www.cnblogs.com/rocky-AGE-24/p/5093113.html
Copyright © 2011-2022 走看看