Command Pattern References
https://refactoring.guru/design-patterns/command
http://aeternum.egloos.com/v/2948571
Definition Behavioral design pattern A pattern that encapsulates behavior in an object and delegates requests to the encapsulated object. A design pattern that turns a request into a stand-alone object containing all information about the request. This allows you to parameterize methods with different requests, delay or queue request execution, and support undoable operations. Situation - Building a Text Editor App Suppose you are building a text editor app like Hangul or Word. Problem How should you build a toolbar with various buttons? Bad Approach - Creating Subclasses #### Method - Create a subclass of Button for each button, with the code to execute for that button. #### Problems 1. Many subclasses are created. - If the Button class changes, its subclasses may break. 2. Duplication can occur. - For example, SaveButton, SaveMenuItem, and SaveShortcut all perform the same save operation but are implemented as different classes. Solution - Layering, Delegating Cause of the Problem This happens because the roles of the GUI and business logic are not separated. Applying SRP (Single Responsibility Principle) solves this, usually by layering. Method Layering - The GUI renders images, receives input, sends requests with parameters to the business logic, and displays the result. - The business logic performs the requested operation. Command Pattern The Command Pattern goes further by preventing the GUI from calling business logic directly. Implementation Steps Extract detailed requests into separate command classes, each with a method to trigger the request (usually with no parameters). The details of the request (which object, which method, which arguments) are encapsulated in the command object. Command objects act as a link between various GUI and business logic objects. The GUI only needs to call the execute method of the appropriate command, without knowing about the business logic object. Implement all commands with the same interface. Benefits: The GUI does not depend on specific commands. The GUI’s behavior can be changed at runtime. Commands can be stored in containers. Question - What about parameters? Command methods do not take parameters, but business logic often needs them. How is this handled? Parameters are considered part of the detailed request. You implement a command class for each combination of business logic and parameters. Thus, the command pattern structure in this example is as follows: No need to create many subclasses. The Button class only needs a reference to a command object. All buttons for the save operation can use the same save command without duplication. Additional benefits:
...