Design Mode JAVA-Command Mode

Article Directory

1. Command mode

1.1 Scene

  1. We bought a set of smart appliances, including lighting, fans, refrigerators, washing machines, which we can control by simply installing apps on our mobile phones.
  2. These smart home appliances come from different manufacturers. We don't want to install an App for each kind of home appliances and control them separately. We hope that only one app can control all smart home appliances.
  3. To achieve the need for an app to control all smart home appliances, each smart home power plant owner needs to provide a unified interface for app calls, so command mode can be considered.
  4. Command mode decouples the Requester of Action from the Executor of Action object.
  5. In our example, the requester of the action is the mobile app, and the executor of the action is an appliances product of each manufacturer

Now write a light on and off command

1.2 Command Mode

Basic Introduction

  1. Command Pattern: In software design, we often need to send requests to certain objects, but we don't know who the recipient of the request is or what the requested operation is. We just need to specify the specific recipient of the request when the program is running. In this case, we can use command mode to design.
  2. Naming patterns make the request sender and the request receiver uncouple each other, making the call relationship between objects more flexible and decoupling.
  3. In naming mode, a request is encapsulated as an object so that different parameters are used to represent different requests (that is, naming), and command mode also supports revocable operations.
  4. Common sense: the general issues orders and the soldier executes them.There are several roles: general (issuer of command), soldier (specific executor of command), command (connection of general and soldier).
    Invoker is the caller (general), Receiver is the callee (soldier), MyCommand is the command, implements the Command interface, and holds the receiving object


Description of the schematic class diagram - i.e. (roles and responsibilities of the naming pattern)

  1. Invoker is the caller role
  2. Command: is a command role, where all commands that need to be executed can be interfaces or abstract classes
  3. Receiver: Receiver role, knowing how to perform and execute a request-related operation
  4. ConcreteCommand: binds a recipient object to an action, invokes the recipient's corresponding action, and implements execute

Client Call
As you know, first specify a command interface, then implement the method in the interface with the specific command (turn on and turn off the light), then bind the receiver (the processing class corresponding to the turn on and turn off command) with the specific command, then call the remote control class to make the command call.
1

public class Client {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//Use the command design mode to complete the operation of the lamp through the remote control
		
		//Create the object of the lamp (recipient)
		LightReceiver lightReceiver = new LightReceiver();
		
		//Create lamp-related switch commands
		LightOnCommand lightOnCommand = new LightOnCommand(lightReceiver);
		LightOffCommand lightOffCommand = new LightOffCommand(lightReceiver);
		
		//Need a remote control
		RemoteController remoteController = new RemoteController();
		
		//Set commands for our remote control, such as no = 0, to turn the lights on and off
		remoteController.setCommand(0, lightOnCommand, lightOffCommand);
		
		System.out.println("--------Press the light on button-----------");
		remoteController.onButtonWasPushed(0);
		System.out.println("--------Press the light off button-----------");
		remoteController.offButtonWasPushed(0);
		System.out.println("--------Press the Undo button-----------");
		remoteController.undoButtonWasPushed();
		
		
		//System.out.println("==========Operate TV with remote control========");
		
		//TVReceiver tvReceiver = new TVReceiver();
		
		//TVOffCommand tvOffCommand = new TVOffCommand(tvReceiver);
		//TVOnCommand tvOnCommand = new TVOnCommand(tvReceiver);
		
		//Set commands for our remote control, such as no = 1 for TV on and off
		//remoteController.setCommand(1, tvOnCommand, tvOffCommand);
		
		//System.out.println("--------- Press the on button of the TV---------");
		//remoteController.onButtonWasPushed(1);
		//System.out.println("----------- press the TV off button---------");
		//remoteController.offButtonWasPushed(1);
		//System.out.println("----------- Press the Undo button-------");
		//remoteController.undoButtonWasPushed();

	}

}

2

//Create Command Interface
public interface Command {

	//Perform actions (actions)
	public void execute();
	//Undo Action (Action)
	public void undo();
}

3

public class LightOffCommand implements Command {

	// Aggregate LightReceiver

	LightReceiver light;

	// constructor
	public LightOffCommand(LightReceiver light) {
			super();
			this.light = light;
		}

	@Override
	public void execute() {
		// TODO Auto-generated method stub
		// Call recipient's method
		light.off();
	}

	@Override
	public void undo() {
		// TODO Auto-generated method stub
		// Call recipient's method
		light.on();
	}
}
public class LightOnCommand implements Command {

	//Aggregate LightReceiver
	
	LightReceiver light;
	
	//constructor
	public LightOnCommand(LightReceiver light) {
		super();
		this.light = light;
	}
	
	@Override
	public void execute() {
		// TODO Auto-generated method stub
		//Call recipient's method
		light.on();
	}

	

	@Override
	public void undo() {
		// TODO Auto-generated method stub
		//Call recipient's method
		light.off();
	}

}

4

public class LightReceiver {

	public void on() {
		System.out.println(" The light is on.. ");
	}
	
	public void off() {
		System.out.println(" The light is off.. ");
	}
}

5

/**
 * No command, empty execution: used to initialize each button, when an empty command is called, the object does nothing
 * In fact, this is a design pattern that eliminates empty judgments
 * @author Administrator
 *
 */
public class NoCommand implements Command {

	@Override
	public void execute() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void undo() {
		// TODO Auto-generated method stub
		
	}

}

6

public class RemoteController {

	// Array of open button commands
	Command[] onCommands;
	Command[] offCommands;

	// Execute Undo Command
	Command undoCommand;

	// Constructor, complete initialization of buttons

	public RemoteController() {

		onCommands = new Command[5];
		offCommands = new Command[5];

		for (int i = 0; i < 5; i++) {
			onCommands[i] = new NoCommand();
			offCommands[i] = new NoCommand();
		}
	}

	// Set up the commands you need for our buttons
	public void setCommand(int no, Command onCommand, Command offCommand) {
		onCommands[no] = onCommand;
		offCommands[no] = offCommand;
	}

	// Press the open button
	public void onButtonWasPushed(int no) { // no 0
		// Find the on button you pressed and call the corresponding method
		onCommands[no].execute();
		// Record this action for undo
		undoCommand = onCommands[no];

	}

	// Press the open button
	public void offButtonWasPushed(int no) { // no 0
		// Find the button for the level you pressed and call the corresponding method
		offCommands[no].execute();
		// Record this action for undo
		undoCommand = offCommands[no];

	}
	
	// Press the Undo button
	public void undoButtonWasPushed() {
		undoCommand.undo();
	}

}

1.3 Command Mode Applied in Spring Framework JdbcTemplate


StatementCallback interface, similar to Command

  • classQueryStatementCallbackimplementsStatementCallback, SqlProvider, anonymous internal class, implements the command interface and acts as a command receiver
  • The command caller is JdbcTemplate, where the action.doInStatement method is called in the execute (StatementCallback action) method. Different objects implementing the StatementCallback interface correspond to different doInStatement implementation logic
  • Another subclass that implements the StatementCallback command interface is QueryStatementCallback,

1.4 Notes and Details for Command Mode

  1. Decouple the object that initiated the request from the object that executed it.The object that initiates the request is the caller. The caller can make the receiver work by calling the execute() method of the command object without knowing who the specific recipient object is and how it is implemented. The command object is responsible for letting the receiver perform the requested action, that is, decoupling between the "request originator" and "request executor" is through the command objectImplemented, the command object acts as a bridge.
  2. It is easy to design a command queue.Multithreaded execution of commands is possible as long as command objects are queued
  3. Easy revocation and redo of requests
  4. Insufficient command mode: may cause some systems to have too many specific command classes, which increases the complexity of the system, which should be noted when using
  5. Empty commands are also a design pattern that eliminates the need for null commands.In the above example, if no empty command is used, each time we press
    All keys need to be empty, which brings us some trouble in coding.
  6. Command mode classic scenario: one button in the interface is a command, a revocation/recovery, trigger-feedback mechanism that simulates CMD (DOS command) orders
151 original articles were published. 17 were praised. 10,000 visits+
Private letter follow

Tags: Spring Mobile

Posted on Sun, 09 Feb 2020 01:29:34 -0500 by emcb_php