What is command mode
The command mode encapsulates the request (command) as an object, so that you can use different requests to parameterize other objects (inject different request dependencies into other objects), and can support the queuing execution of requests (commands), log recording, and revocation ( Additional control) function.
Much like the strategy mode, we can't use coding to distinguish modes, but application scenarios
Code
/ ** * Abstract command * / public interface Command { void execute (); } / ** * Specific command processing * / public class GotDiamondCommand implements Command { // Omit member variables public GotDiamondCommand ( / * Data * / ) { // ... } @Override public void execute () { // Execute the corresponding logic } } // GotStartCommand / HitObstacleCommand / ArchiveCommand class omit public classGameApplication { private static final int MAX_HANDLED_REQ_COUNT_PER_LOOP = 100 ; // Store commands to the queue private Queue <Command> queue = new LinkedList <> (); public void mainloop () { while ( true ) { List <Request> requests = new ArrayList <> (); // Omit the logic of fetching data from epoll or select, and encapsulate it as Request, // Note to set the timeout time, if the request is not received for a long time, continue the following logic processing. for (Request request: requests) { Event event = request.getEvent(); Command command = null; if (event.equals(Event.GOT_DIAMOND)) { command = new GotDiamondCommand(/*数据*/); } else if (event.equals(Event.GOT_STAR)) { command = new GotStartCommand(/*数据*/); } else if (event.equals(Event.HIT_OBSTACLE)) { command = newHitObstacleCommand ( / * data * / ); } else if (event.equals (Event.ARCHIVE)) { command = new ArchiveCommand ( / * data * / ); } // ... a bunch of else if ... queue. add (command); } int handledCount = 0 ; / ** * traverse the execution command * / while (handledCount < MAX_HANDLED_REQ_COUNT_PER_LOOP) { if (queue.isEmpty ()) { break; } Command command = queue.poll(); command.execute(); } } } }