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