设计模式-命令模式

命令模式

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

 

第一步,创建接口

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

    }

}

 

 

原文地址:https://www.cnblogs.com/rocky-AGE-24/p/5093113.html