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

        }

    }

     

     

  • 相关阅读:
    C语言I博客作业08
    C语言I博客作业07
    第十周助教总结
    关于Dev-c++运行时与Windows不兼容问题
    C语言I博客作业06
    第九周助教总结
    C语言I作业07
    C语言I博客作业06
    C语言I作业05

  • 原文地址:https://www.cnblogs.com/rocky-AGE-24/p/5093113.html
Copyright © 2011-2022 走看看