1. Command mode Overview

The command pattern is a data-driven design pattern. The request is wrapped in the object as a command and passed to the calling object. The calling object looks for a suitable object that can handle the command and passes the command to the corresponding object, which executes the command.

(1) Application

Loose coupling of requester and implementer can be achieved by encapsulating a request or behavior as an object to process. This is very convenient for recording, revoking, and so on.

(2) advantages

Reduces system coupling and makes it easy to add new commands.

(3) the disadvantages

The system may have too many command classes.

2. Command mode instance

The command mode is used here to simulate the process of SCORING NBA players.

(1) Implement abstract class Score

public abstract class Score {
    int point;
}
Copy the code

(2) To achieve two-point ball and three-point ball categories

public class TwoPointer extends Score { public TwoPointer() { point = 2; }}Copy the code
public class ThreePointer extends Score { public ThreePointer() { point = 3; }}Copy the code

(3) Implement the player class

public class Player { private String name; private int total; public Player(String name) { this.name = name; this.total = 0; } /** * total */ public void getTotal() {system.out.println (name + "currentscore:" + total); } /** * score */ public void score(score score) {system.out.println (name + "score" + score. Point + "score") ); total += score.point; } /** * public void undo(Score Score) {system.out.println (name + "+ Score. Point +"); ); total -= score.point; }}Copy the code

(4) The game begins

Public class Game {public static void main(String[] args) {Player kobe = new Player(" kobe "); Player curry = new Player(" curry "); // TwoPointer TwoPointer = new TwoPointer(); // ThreePointer ThreePointer = new ThreePointer(); // Kobe scores two points; kobe.getTotal(); // Curry makes a 3 pointer curry.getTotal(); Curry. undo(threePointer); // Curry. threePointer; curry.score(twoPointer); curry.getTotal(); }}Copy the code

Running results:

3. Some thinking

In the example above, the commands “make a 2-pointer” and “make a 3-pointer” are encapsulated as objects that can be processed directly after Bryant and Curry score. If the referee changes his decision, he can easily reverse it. If you need to introduce a quad, you just need to implement a “make a quad” command class.

Refer to the reference

Command mode: www.runoob.com/design-patt…