Design mode-Command mode

Source: Internet
Author: User

Command mode

A method to complete a function , Most of the steps to complete this function have been determined , But there are a few steps cannot be determined , You must wait until the execution method to determine

The first step is to create the interface

Package Study.command;

/**

* Interface of the command class

* @author Rocky

*

*/

public interface Command

{

/**

* methods that can be used for multiple implementation classes

* @param array

*/

void process (int[] array);

}

The second step implements the interface and implements the method

Import Study.command.Command;

/**

* Implementation of command class, with printing function

* @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;

/**

* Interface for summing functions

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

}

}

Step three, using command mode

Package study.commandtest;

Import Study.command.Command;

Import Study.commandImpl.PrintCommand;

Import Study.commandImpl.SumCommand;

/**

* Class to test the command pattern

* @author Rocky

*

*/

public class Tstcommand

{

/**

*

* @param array of arrays tested

* @param the implementation class of the command class, passing in the corresponding implementation class as required

*/

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

}

}

Design mode-Command mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.