đŸ•·ïž Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 167 (from laksa010)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

â„č Skipped - page is already crawled

📄
INDEXABLE
✅
CRAWLED
2 hours ago
đŸ€–
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://refactoring.guru/design-patterns/command
Last Crawled2026-04-06 10:56:56 (2 hours ago)
First Indexed2017-04-06 19:23:31 (9 years ago)
HTTP Status Code200
Meta TitleCommand
Meta DescriptionCommand is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request's execution, and support undoable operations.
Meta Canonicalnull
Boilerpipe Text
Also known as: Action,  Transaction Intent Command is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations. Problem Imagine that you’re working on a new text-editor app. Your current task is to create a toolbar with a bunch of buttons for various operations of the editor. You created a very neat Button class that can be used for buttons on the toolbar, as well as for generic buttons in various dialogs. All buttons of the app are derived from the same class. While all of these buttons look similar, they’re all supposed to do different things. Where would you put the code for the various click handlers of these buttons? The simplest solution is to create tons of subclasses for each place where the button is used. These subclasses would contain the code that would have to be executed on a button click. Lots of button subclasses. What can go wrong? Before long, you realize that this approach is deeply flawed. First, you have an enormous number of subclasses, and that would be okay if you weren’t risking breaking the code in these subclasses each time you modify the base Button class. Put simply, your GUI code has become awkwardly dependent on the volatile code of the business logic. Several classes implement the same functionality. And here’s the ugliest part. Some operations, such as copying/pasting text, would need to be invoked from multiple places. For example, a user could click a small “Copy” button on the toolbar, or copy something via the context menu, or just hit Ctrl+C on the keyboard. Initially, when our app only had the toolbar, it was okay to place the implementation of various operations into the button subclasses. In other words, having the code for copying text inside the CopyButton subclass was fine. But then, when you implement context menus, shortcuts, and other stuff, you have to either duplicate the operation’s code in many classes or make menus dependent on buttons, which is an even worse option. Solution Good software design is often based on the principle of separation of concerns , which usually results in breaking an app into layers. The most common example: a layer for the graphical user interface and another layer for the business logic. The GUI layer is responsible for rendering a beautiful picture on the screen, capturing any input and showing results of what the user and the app are doing. However, when it comes to doing something important, like calculating the trajectory of the moon or composing an annual report, the GUI layer delegates the work to the underlying layer of business logic. In the code it might look like this: a GUI object calls a method of a business logic object, passing it some arguments. This process is usually described as one object sending another a request . The GUI objects may access the business logic objects directly. The Command pattern suggests that GUI objects shouldn’t send these requests directly. Instead, you should extract all of the request details, such as the object being called, the name of the method and the list of arguments into a separate command class with a single method that triggers this request. Command objects serve as links between various GUI and business logic objects. From now on, the GUI object doesn’t need to know what business logic object will receive the request and how it’ll be processed. The GUI object just triggers the command, which handles all the details. Accessing the business logic layer via a command. The next step is to make your commands implement the same interface. Usually it has just a single execution method that takes no parameters. This interface lets you use various commands with the same request sender, without coupling it to concrete classes of commands. As a bonus, now you can switch command objects linked to the sender, effectively changing the sender’s behavior at runtime. You might have noticed one missing piece of the puzzle, which is the request parameters. A GUI object might have supplied the business-layer object with some parameters. Since the command execution method doesn’t have any parameters, how would we pass the request details to the receiver? It turns out the command should be either pre-configured with this data, or capable of getting it on its own. The GUI objects delegate the work to commands. Let’s get back to our text editor. After we apply the Command pattern, we no longer need all those button subclasses to implement various click behaviors. It’s enough to put a single field into the base Button class that stores a reference to a command object and make the button execute that command on a click. You’ll implement a bunch of command classes for every possible operation and link them with particular buttons, depending on the buttons’ intended behavior. Other GUI elements, such as menus, shortcuts or entire dialogs, can be implemented in the same way. They’ll be linked to a command which gets executed when a user interacts with the GUI element. As you’ve probably guessed by now, the elements related to the same operations will be linked to the same commands, preventing any code duplication. As a result, commands become a convenient middle layer that reduces coupling between the GUI and business logic layers. And that’s only a fraction of the benefits that the Command pattern can offer! Real-World Analogy Making an order in a restaurant. After a long walk through the city, you get to a nice restaurant and sit at the table by the window. A friendly waiter approaches you and quickly takes your order, writing it down on a piece of paper. The waiter goes to the kitchen and sticks the order on the wall. After a while, the order gets to the chef, who reads it and cooks the meal accordingly. The cook places the meal on a tray along with the order. The waiter discovers the tray, checks the order to make sure everything is as you wanted it, and brings everything to your table. The paper order serves as a command. It remains in a queue until the chef is ready to serve it. The order contains all the relevant information required to cook the meal. It allows the chef to start cooking right away instead of running around clarifying the order details from you directly. Structure The Sender class (aka invoker ) is responsible for initiating requests. This class must have a field for storing a reference to a command object. The sender triggers that command instead of sending the request directly to the receiver. Note that the sender isn’t responsible for creating the command object. Usually, it gets a pre-created command from the client via the constructor. The Command interface usually declares just a single method for executing the command. Concrete Commands implement various kinds of requests. A concrete command isn’t supposed to perform the work on its own, but rather to pass the call to one of the business logic objects. However, for the sake of simplifying the code, these classes can be merged. Parameters required to execute a method on a receiving object can be declared as fields in the concrete command. You can make command objects immutable by only allowing the initialization of these fields via the constructor. The Receiver class contains some business logic. Almost any object may act as a receiver. Most commands only handle the details of how a request is passed to the receiver, while the receiver itself does the actual work. The Client creates and configures concrete command objects. The client must pass all of the request parameters, including a receiver instance, into the command’s constructor. After that, the resulting command may be associated with one or multiple senders. Pseudocode In this example, the Command pattern helps to track the history of executed operations and makes it possible to revert an operation if needed. Undoable operations in a text editor. Commands which result in changing the state of the editor (e.g., cutting and pasting) make a backup copy of the editor’s state before executing an operation associated with the command. After a command is executed, it’s placed into the command history (a stack of command objects) along with the backup copy of the editor’s state at that point. Later, if the user needs to revert an operation, the app can take the most recent command from the history, read the associated backup of the editor’s state, and restore it. The client code (GUI elements, command history, etc.) isn’t coupled to concrete command classes because it works with commands via the command interface. This approach lets you introduce new commands into the app without breaking any existing code. // The base command class defines the common interface for all // concrete commands. abstract class Command is protected field app: Application protected field editor: Editor protected field backup: text constructor Command(app: Application, editor: Editor) is this.app = app this.editor = editor // Make a backup of the editor's state. method saveBackup() is backup = editor.text // Restore the editor's state. method undo() is editor.text = backup // The execution method is declared abstract to force all // concrete commands to provide their own implementations. // The method must return true or false depending on whether // the command changes the editor's state. abstract method execute() // The concrete commands go here. class CopyCommand extends Command is // The copy command isn't saved to the history since it // doesn't change the editor's state. method execute() is app.clipboard = editor.getSelection() return false class CutCommand extends Command is // The cut command does change the editor's state, therefore // it must be saved to the history. And it'll be saved as // long as the method returns true. method execute() is saveBackup() app.clipboard = editor.getSelection() editor.deleteSelection() return true class PasteCommand extends Command is method execute() is saveBackup() editor.replaceSelection(app.clipboard) return true // The undo operation is also a command. class UndoCommand extends Command is method execute() is app.undo() return false // The global command history is just a stack. class CommandHistory is private field history: array of Command // Last in... method push(c: Command) is // Push the command to the end of the history array. // ...first out method pop():Command is // Get the most recent command from the history. // The editor class has actual text editing operations. It plays // the role of a receiver: all commands end up delegating // execution to the editor's methods. class Editor is field text: string method getSelection() is // Return selected text. method deleteSelection() is // Delete selected text. method replaceSelection(text) is // Insert the clipboard's contents at the current // position. // The application class sets up object relations. It acts as a // sender: when something needs to be done, it creates a command // object and executes it. class Application is field clipboard: string field editors: array of Editors field activeEditor: Editor field history: CommandHistory // The code which assigns commands to UI objects may look // like this. method createUI() is // ... copy = function() { executeCommand( new CopyCommand(this, activeEditor)) } copyButton.setCommand(copy) shortcuts.onKeyPress("Ctrl+C", copy) cut = function() { executeCommand( new CutCommand(this, activeEditor)) } cutButton.setCommand(cut) shortcuts.onKeyPress("Ctrl+X", cut) paste = function() { executeCommand( new PasteCommand(this, activeEditor)) } pasteButton.setCommand(paste) shortcuts.onKeyPress("Ctrl+V", paste) undo = function() { executeCommand( new UndoCommand(this, activeEditor)) } undoButton.setCommand(undo) shortcuts.onKeyPress("Ctrl+Z", undo) // Execute a command and check whether it has to be added to // the history. method executeCommand(command) is if (command.execute()) history.push(command) // Take the most recent command from the history and run its // undo method. Note that we don't know the class of that // command. But we don't have to, since the command knows // how to undo its own action. method undo() is command = history.pop() if (command != null) command.undo() Applicability Use the Command pattern when you want to parameterize objects with operations. The Command pattern can turn a specific method call into a stand-alone object. This change opens up a lot of interesting uses: you can pass commands as method arguments, store them inside other objects, switch linked commands at runtime, etc. Here’s an example: you’re developing a GUI component such as a context menu, and you want your users to be able to configure menu items that trigger operations when an end user clicks an item. Use the Command pattern when you want to queue operations, schedule their execution, or execute them remotely. As with any other object, a command can be serialized, which means converting it to a string that can be easily written to a file or a database. Later, the string can be restored as the initial command object. Thus, you can delay and schedule command execution. But there’s even more! In the same way, you can queue, log or send commands over the network. Use the Command pattern when you want to implement reversible operations. Although there are many ways to implement undo/redo, the Command pattern is perhaps the most popular of all. To be able to revert operations, you need to implement the history of performed operations. The command history is a stack that contains all executed command objects along with related backups of the application’s state. This method has two drawbacks. First, it isn’t that easy to save an application’s state because some of it can be private. This problem can be mitigated with the Memento pattern. Second, the state backups may consume quite a lot of RAM. Therefore, sometimes you can resort to an alternative implementation: instead of restoring the past state, the command performs the inverse operation. The reverse operation also has a price: it may turn out to be hard or even impossible to implement. How to Implement Declare the command interface with a single execution method. Start extracting requests into concrete command classes that implement the command interface. Each class must have a set of fields for storing the request arguments along with a reference to the actual receiver object. All these values must be initialized via the command’s constructor. Identify classes that will act as senders . Add the fields for storing commands into these classes. Senders should communicate with their commands only via the command interface. Senders usually don’t create command objects on their own, but rather get them from the client code. Change the senders so they execute the command instead of sending a request to the receiver directly. The client should initialize objects in the following order: Create receivers. Create commands, and associate them with receivers if needed. Create senders, and associate them with specific commands. Pros and Cons Single Responsibility Principle . You can decouple classes that invoke operations from classes that perform these operations. Open/Closed Principle . You can introduce new commands into the app without breaking existing client code. You can implement undo/redo. You can implement deferred execution of operations. You can assemble a set of simple commands into a complex one. The code may become more complicated since you’re introducing a whole new layer between senders and receivers. Relations with Other Patterns Chain of Responsibility , Command , Mediator and Observer address various ways of connecting senders and receivers of requests: Chain of Responsibility passes a request sequentially along a dynamic chain of potential receivers until one of them handles it. Command establishes unidirectional connections between senders and receivers. Mediator eliminates direct connections between senders and receivers, forcing them to communicate indirectly via a mediator object. Observer lets receivers dynamically subscribe to and unsubscribe from receiving requests. Handlers in Chain of Responsibility can be implemented as Commands . In this case, you can execute a lot of different operations over the same context object, represented by a request. However, there’s another approach, where the request itself is a Command object. In this case, you can execute the same operation in a series of different contexts linked into a chain. You can use Command and Memento together when implementing “undo”. In this case, commands are responsible for performing various operations over a target object, while mementos save the state of that object just before a command gets executed. Command and Strategy may look similar because you can use both to parameterize an object with some action. However, they have very different intents. You can use Command to convert any operation into an object. The operation’s parameters become fields of that object. The conversion lets you defer execution of the operation, queue it, store the history of commands, send commands to remote services, etc. On the other hand, Strategy usually describes different ways of doing the same thing, letting you swap these algorithms within a single context class. Prototype can help when you need to save copies of Commands into history. You can treat Visitor as a powerful version of the Command pattern. Its objects can execute operations over various objects of different classes.
Markdown
[![](https://gitbybit.com/images/icons/cat-not-looking.svg) ![](https://gitbybit.com/images/icons/cat-open-mouth.webp) ![](https://gitbybit.com/images/icons/cat-laughing.svg) Check out my new Git course! Hey! Check out my new Git course! Hey! Check out my new Git course on GitByBit.com! Hey! Want a cool refresher on Git? Check out my new Git course on GitByBit.com! ![](https://gitbybit.com/images/icons/cat-cool.webp) ![](https://gitbybit.com/images/icons/cat-blowing.webp) ![](https://gitbybit.com/images/icons/cat-laughing2.webp)](https://gitbybit.com/) / [Design Patterns](https://refactoring.guru/design-patterns) / [Behavioral Patterns](https://refactoring.guru/design-patterns/behavioral-patterns) # Command Also known as: Action, Transaction ## Intent **Command** is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations. ![Command design pattern](https://refactoring.guru/images/patterns/content/command/command-en.png?id=80fbadc666cf3b9b1958c546d2746ca4) ## Problem Imagine that you’re working on a new text-editor app. Your current task is to create a toolbar with a bunch of buttons for various operations of the editor. You created a very neat `Button` class that can be used for buttons on the toolbar, as well as for generic buttons in various dialogs. ![Problem solved by the Command pattern](https://refactoring.guru/images/patterns/diagrams/command/problem1.png?id=84189315a0e8d91da262792979005ab4) All buttons of the app are derived from the same class. While all of these buttons look similar, they’re all supposed to do different things. Where would you put the code for the various click handlers of these buttons? The simplest solution is to create tons of subclasses for each place where the button is used. These subclasses would contain the code that would have to be executed on a button click. ![Lots of button subclasses](https://refactoring.guru/images/patterns/diagrams/command/problem2.png?id=f0e33da1842b3a3ee3b4857de0b6ec93) Lots of button subclasses. What can go wrong? Before long, you realize that this approach is deeply flawed. First, you have an enormous number of subclasses, and that would be okay if you weren’t risking breaking the code in these subclasses each time you modify the base `Button` class. Put simply, your GUI code has become awkwardly dependent on the volatile code of the business logic. ![Several classes implement the same functionality](https://refactoring.guru/images/patterns/diagrams/command/problem3-en.png?id=1fbd56ae7ba3e3dfac45cfa2de6db450) Several classes implement the same functionality. And here’s the ugliest part. Some operations, such as copying/pasting text, would need to be invoked from multiple places. For example, a user could click a small “Copy” button on the toolbar, or copy something via the context menu, or just hit `Ctrl+C` on the keyboard. Initially, when our app only had the toolbar, it was okay to place the implementation of various operations into the button subclasses. In other words, having the code for copying text inside the `CopyButton` subclass was fine. But then, when you implement context menus, shortcuts, and other stuff, you have to either duplicate the operation’s code in many classes or make menus dependent on buttons, which is an even worse option. ## Solution Good software design is often based on the *principle of separation of concerns*, which usually results in breaking an app into layers. The most common example: a layer for the graphical user interface and another layer for the business logic. The GUI layer is responsible for rendering a beautiful picture on the screen, capturing any input and showing results of what the user and the app are doing. However, when it comes to doing something important, like calculating the trajectory of the moon or composing an annual report, the GUI layer delegates the work to the underlying layer of business logic. In the code it might look like this: a GUI object calls a method of a business logic object, passing it some arguments. This process is usually described as one object sending another a *request*. ![The GUI layer may access the business logic layer directly](https://refactoring.guru/images/patterns/diagrams/command/solution1-en.png?id=ec37db1713fe2c1a9318886590667cfb) The GUI objects may access the business logic objects directly. The Command pattern suggests that GUI objects shouldn’t send these requests directly. Instead, you should extract all of the request details, such as the object being called, the name of the method and the list of arguments into a separate *command* class with a single method that triggers this request. Command objects serve as links between various GUI and business logic objects. From now on, the GUI object doesn’t need to know what business logic object will receive the request and how it’ll be processed. The GUI object just triggers the command, which handles all the details. ![Accessing the business logic layer via a command.](https://refactoring.guru/images/patterns/diagrams/command/solution2-en.png?id=63bcac5cde2ec536c3329eff4c385839) Accessing the business logic layer via a command. The next step is to make your commands implement the same interface. Usually it has just a single execution method that takes no parameters. This interface lets you use various commands with the same request sender, without coupling it to concrete classes of commands. As a bonus, now you can switch command objects linked to the sender, effectively changing the sender’s behavior at runtime. You might have noticed one missing piece of the puzzle, which is the request parameters. A GUI object might have supplied the business-layer object with some parameters. Since the command execution method doesn’t have any parameters, how would we pass the request details to the receiver? It turns out the command should be either pre-configured with this data, or capable of getting it on its own. ![The GUI objects delegate the work to commands](https://refactoring.guru/images/patterns/diagrams/command/solution3-en.png?id=c92f6874b95de46b041499d41234b00b) The GUI objects delegate the work to commands. Let’s get back to our text editor. After we apply the Command pattern, we no longer need all those button subclasses to implement various click behaviors. It’s enough to put a single field into the base `Button` class that stores a reference to a command object and make the button execute that command on a click. You’ll implement a bunch of command classes for every possible operation and link them with particular buttons, depending on the buttons’ intended behavior. Other GUI elements, such as menus, shortcuts or entire dialogs, can be implemented in the same way. They’ll be linked to a command which gets executed when a user interacts with the GUI element. As you’ve probably guessed by now, the elements related to the same operations will be linked to the same commands, preventing any code duplication. As a result, commands become a convenient middle layer that reduces coupling between the GUI and business logic layers. And that’s only a fraction of the benefits that the Command pattern can offer\! ## Real-World Analogy ![Making an order in a restaurant](https://refactoring.guru/images/patterns/content/command/command-comic-1.png?id=551df832f445080976f3116e0dc120c9) Making an order in a restaurant. After a long walk through the city, you get to a nice restaurant and sit at the table by the window. A friendly waiter approaches you and quickly takes your order, writing it down on a piece of paper. The waiter goes to the kitchen and sticks the order on the wall. After a while, the order gets to the chef, who reads it and cooks the meal accordingly. The cook places the meal on a tray along with the order. The waiter discovers the tray, checks the order to make sure everything is as you wanted it, and brings everything to your table. The paper order serves as a command. It remains in a queue until the chef is ready to serve it. The order contains all the relevant information required to cook the meal. It allows the chef to start cooking right away instead of running around clarifying the order details from you directly. ## Structure ![Structure of the Command design pattern](https://refactoring.guru/images/patterns/diagrams/command/structure.png?id=1cd7833638f4c43630f4a84017d31195)![Structure of the Command design pattern](https://refactoring.guru/images/patterns/diagrams/command/structure-indexed.png?id=95529d7282dc7bc1c5bc443423b1cf4f) 1. The **Sender** class (aka *invoker*) is responsible for initiating requests. This class must have a field for storing a reference to a command object. The sender triggers that command instead of sending the request directly to the receiver. Note that the sender isn’t responsible for creating the command object. Usually, it gets a pre-created command from the client via the constructor. 2. The **Command** interface usually declares just a single method for executing the command. 3. **Concrete Commands** implement various kinds of requests. A concrete command isn’t supposed to perform the work on its own, but rather to pass the call to one of the business logic objects. However, for the sake of simplifying the code, these classes can be merged. Parameters required to execute a method on a receiving object can be declared as fields in the concrete command. You can make command objects immutable by only allowing the initialization of these fields via the constructor. 4. The **Receiver** class contains some business logic. Almost any object may act as a receiver. Most commands only handle the details of how a request is passed to the receiver, while the receiver itself does the actual work. 5. The **Client** creates and configures concrete command objects. The client must pass all of the request parameters, including a receiver instance, into the command’s constructor. After that, the resulting command may be associated with one or multiple senders. ## Pseudocode In this example, the **Command** pattern helps to track the history of executed operations and makes it possible to revert an operation if needed. ![Structure of the Command pattern example](https://refactoring.guru/images/patterns/diagrams/command/example.png?id=1f42c8395fe54d0e409026b91881e2a0) Undoable operations in a text editor. Commands which result in changing the state of the editor (e.g., cutting and pasting) make a backup copy of the editor’s state before executing an operation associated with the command. After a command is executed, it’s placed into the command history (a stack of command objects) along with the backup copy of the editor’s state at that point. Later, if the user needs to revert an operation, the app can take the most recent command from the history, read the associated backup of the editor’s state, and restore it. The client code (GUI elements, command history, etc.) isn’t coupled to concrete command classes because it works with commands via the command interface. This approach lets you introduce new commands into the app without breaking any existing code. ``` // The base command class defines the common interface for all // concrete commands. abstract class Command is protected field app: Application protected field editor: Editor protected field backup: text constructor Command(app: Application, editor: Editor) is this.app = app this.editor = editor // Make a backup of the editor's state. method saveBackup() is backup = editor.text // Restore the editor's state. method undo() is editor.text = backup // The execution method is declared abstract to force all // concrete commands to provide their own implementations. // The method must return true or false depending on whether // the command changes the editor's state. abstract method execute() // The concrete commands go here. class CopyCommand extends Command is // The copy command isn't saved to the history since it // doesn't change the editor's state. method execute() is app.clipboard = editor.getSelection() return false class CutCommand extends Command is // The cut command does change the editor's state, therefore // it must be saved to the history. And it'll be saved as // long as the method returns true. method execute() is saveBackup() app.clipboard = editor.getSelection() editor.deleteSelection() return true class PasteCommand extends Command is method execute() is saveBackup() editor.replaceSelection(app.clipboard) return true // The undo operation is also a command. class UndoCommand extends Command is method execute() is app.undo() return false // The global command history is just a stack. class CommandHistory is private field history: array of Command // Last in... method push(c: Command) is // Push the command to the end of the history array. // ...first out method pop():Command is // Get the most recent command from the history. // The editor class has actual text editing operations. It plays // the role of a receiver: all commands end up delegating // execution to the editor's methods. class Editor is field text: string method getSelection() is // Return selected text. method deleteSelection() is // Delete selected text. method replaceSelection(text) is // Insert the clipboard's contents at the current // position. // The application class sets up object relations. It acts as a // sender: when something needs to be done, it creates a command // object and executes it. class Application is field clipboard: string field editors: array of Editors field activeEditor: Editor field history: CommandHistory // The code which assigns commands to UI objects may look // like this. method createUI() is // ... copy = function() { executeCommand( new CopyCommand(this, activeEditor)) } copyButton.setCommand(copy) shortcuts.onKeyPress("Ctrl+C", copy) cut = function() { executeCommand( new CutCommand(this, activeEditor)) } cutButton.setCommand(cut) shortcuts.onKeyPress("Ctrl+X", cut) paste = function() { executeCommand( new PasteCommand(this, activeEditor)) } pasteButton.setCommand(paste) shortcuts.onKeyPress("Ctrl+V", paste) undo = function() { executeCommand( new UndoCommand(this, activeEditor)) } undoButton.setCommand(undo) shortcuts.onKeyPress("Ctrl+Z", undo) // Execute a command and check whether it has to be added to // the history. method executeCommand(command) is if (command.execute()) history.push(command) // Take the most recent command from the history and run its // undo method. Note that we don't know the class of that // command. But we don't have to, since the command knows // how to undo its own action. method undo() is command = history.pop() if (command != null) command.undo() ``` ## Applicability Use the Command pattern when you want to parameterize objects with operations. The Command pattern can turn a specific method call into a stand-alone object. This change opens up a lot of interesting uses: you can pass commands as method arguments, store them inside other objects, switch linked commands at runtime, etc. Here’s an example: you’re developing a GUI component such as a context menu, and you want your users to be able to configure menu items that trigger operations when an end user clicks an item. Use the Command pattern when you want to queue operations, schedule their execution, or execute them remotely. As with any other object, a command can be serialized, which means converting it to a string that can be easily written to a file or a database. Later, the string can be restored as the initial command object. Thus, you can delay and schedule command execution. But there’s even more! In the same way, you can queue, log or send commands over the network. Use the Command pattern when you want to implement reversible operations. Although there are many ways to implement undo/redo, the Command pattern is perhaps the most popular of all. To be able to revert operations, you need to implement the history of performed operations. The command history is a stack that contains all executed command objects along with related backups of the application’s state. This method has two drawbacks. First, it isn’t that easy to save an application’s state because some of it can be private. This problem can be mitigated with the [Memento](https://refactoring.guru/design-patterns/memento) pattern. Second, the state backups may consume quite a lot of RAM. Therefore, sometimes you can resort to an alternative implementation: instead of restoring the past state, the command performs the inverse operation. The reverse operation also has a price: it may turn out to be hard or even impossible to implement. ## How to Implement 1. Declare the command interface with a single execution method. 2. Start extracting requests into concrete command classes that implement the command interface. Each class must have a set of fields for storing the request arguments along with a reference to the actual receiver object. All these values must be initialized via the command’s constructor. 3. Identify classes that will act as *senders*. Add the fields for storing commands into these classes. Senders should communicate with their commands only via the command interface. Senders usually don’t create command objects on their own, but rather get them from the client code. 4. Change the senders so they execute the command instead of sending a request to the receiver directly. 5. The client should initialize objects in the following order: - Create receivers. - Create commands, and associate them with receivers if needed. - Create senders, and associate them with specific commands. ## Pros and Cons - *Single Responsibility Principle*. You can decouple classes that invoke operations from classes that perform these operations. - *Open/Closed Principle*. You can introduce new commands into the app without breaking existing client code. - You can implement undo/redo. - You can implement deferred execution of operations. - You can assemble a set of simple commands into a complex one. - The code may become more complicated since you’re introducing a whole new layer between senders and receivers. ## Relations with Other Patterns - [Chain of Responsibility](https://refactoring.guru/design-patterns/chain-of-responsibility), [Command](https://refactoring.guru/design-patterns/command), [Mediator](https://refactoring.guru/design-patterns/mediator) and [Observer](https://refactoring.guru/design-patterns/observer) address various ways of connecting senders and receivers of requests: - *Chain of Responsibility* passes a request sequentially along a dynamic chain of potential receivers until one of them handles it. - *Command* establishes unidirectional connections between senders and receivers. - *Mediator* eliminates direct connections between senders and receivers, forcing them to communicate indirectly via a mediator object. - *Observer* lets receivers dynamically subscribe to and unsubscribe from receiving requests. - Handlers in [Chain of Responsibility](https://refactoring.guru/design-patterns/chain-of-responsibility) can be implemented as [Commands](https://refactoring.guru/design-patterns/command). In this case, you can execute a lot of different operations over the same context object, represented by a request. However, there’s another approach, where the request itself is a *Command* object. In this case, you can execute the same operation in a series of different contexts linked into a chain. - You can use [Command](https://refactoring.guru/design-patterns/command) and [Memento](https://refactoring.guru/design-patterns/memento) together when implementing “undo”. In this case, commands are responsible for performing various operations over a target object, while mementos save the state of that object just before a command gets executed. - [Command](https://refactoring.guru/design-patterns/command) and [Strategy](https://refactoring.guru/design-patterns/strategy) may look similar because you can use both to parameterize an object with some action. However, they have very different intents. - You can use *Command* to convert any operation into an object. The operation’s parameters become fields of that object. The conversion lets you defer execution of the operation, queue it, store the history of commands, send commands to remote services, etc. - On the other hand, *Strategy* usually describes different ways of doing the same thing, letting you swap these algorithms within a single context class. - [Prototype](https://refactoring.guru/design-patterns/prototype) can help when you need to save copies of [Commands](https://refactoring.guru/design-patterns/command) into history. - You can treat [Visitor](https://refactoring.guru/design-patterns/visitor) as a powerful version of the [Command](https://refactoring.guru/design-patterns/command) pattern. Its objects can execute operations over various objects of different classes. ## Code Examples [![Command in C\#](https://refactoring.guru/images/patterns/icons/csharp.svg?id=da64592defc6e86d57c39c66e9de3e58)](https://refactoring.guru/design-patterns/command/csharp/example "Command in C#") [![Command in C++](https://refactoring.guru/images/patterns/icons/cpp.svg?id=f7782ed8b8666246bfcc3f8fefc3b858)](https://refactoring.guru/design-patterns/command/cpp/example "Command in C++") [![Command in Go](https://refactoring.guru/images/patterns/icons/go.svg?id=1a89927eb99b1ea3fde7701d97970aca)](https://refactoring.guru/design-patterns/command/go/example "Command in Go") [![Command in Java](https://refactoring.guru/images/patterns/icons/java.svg?id=e6d87e2dca08c953fe3acd1275ed4f4e)](https://refactoring.guru/design-patterns/command/java/example "Command in Java") [![Command in PHP](https://refactoring.guru/images/patterns/icons/php.svg?id=be1906eb26b71ec1d3b93720d6156618)](https://refactoring.guru/design-patterns/command/php/example "Command in PHP") [![Command in Python](https://refactoring.guru/images/patterns/icons/python.svg?id=6d815d43c0f7050a1151b43e51569c9f)](https://refactoring.guru/design-patterns/command/python/example "Command in Python") [![Command in Ruby](https://refactoring.guru/images/patterns/icons/ruby.svg?id=b065b718c914bf8e960ef731600be1eb)](https://refactoring.guru/design-patterns/command/ruby/example "Command in Ruby") [![Command in Rust](https://refactoring.guru/images/patterns/icons/rust.svg?id=1f5698a4b5ae23fe79413511747e4a87)](https://refactoring.guru/design-patterns/command/rust/example "Command in Rust") [![Command in Swift](https://refactoring.guru/images/patterns/icons/swift.svg?id=0b716c2d52ec3a48fbe91ac031070c1d)](https://refactoring.guru/design-patterns/command/swift/example "Command in Swift") [![Command in TypeScript](https://refactoring.guru/images/patterns/icons/typescript.svg?id=2239d0f16cb703540c205dd8cb0c0cb7)](https://refactoring.guru/design-patterns/command/typescript/example "Command in TypeScript") [![](https://refactoring.guru/images/patterns/banners/patterns-book-banner-3.png?id=7d445df13c80287beaab234b4f3b698c)](https://refactoring.guru/design-patterns/book) ### Support our free website and own the eBook\! - 22 design patterns and 8 principles explained in depth. - 409 well-structured, easy to read, jargon-free pages. - 225 clear and helpful illustrations and diagrams. - An archive with code examples in 11 languages. - All devices supported: PDF/EPUB/MOBI/KFX formats. [Learn more
](https://refactoring.guru/design-patterns/book) #### Read next [Iterator](https://refactoring.guru/design-patterns/iterator) #### Return [Chain of Responsibility](https://refactoring.guru/design-patterns/chain-of-responsibility) [![](https://refactoring.guru/images/patterns/book/web-cover-en.png?id=328861769fd11617674e3b8a7e2dd9e7)](https://refactoring.guru/design-patterns/book) This article is a part of our eBook **Dive Into Design Patterns**. [Learn more
](https://refactoring.guru/design-patterns/book) [![Refactoring.Guru](https://refactoring.guru/images/content-public/logos/logo-new.png?id=97d554614702483f31e38b32e82d8e34)](https://refactoring.guru/) - [Premium Content](https://refactoring.guru/store) - [Design Patterns eBook](https://refactoring.guru/design-patterns/book) - [Refactoring Course](https://refactoring.guru/refactoring/course) - [Refactoring](https://refactoring.guru/refactoring) - [What is Refactoring](https://refactoring.guru/refactoring/what-is-refactoring) - [Clean code](https://refactoring.guru/refactoring/what-is-refactoring) - [Technical debt](https://refactoring.guru/refactoring/technical-debt) - [When to refactor](https://refactoring.guru/refactoring/when) - [How to refactor](https://refactoring.guru/refactoring/how-to) - [Catalog](https://refactoring.guru/refactoring/catalog) - [Code Smells](https://refactoring.guru/refactoring/smells) - [Bloaters](https://refactoring.guru/refactoring/smells/bloaters) - [Long Method](https://refactoring.guru/smells/long-method) - [Large Class](https://refactoring.guru/smells/large-class) - [Primitive Obsession](https://refactoring.guru/smells/primitive-obsession) - [Long Parameter List](https://refactoring.guru/smells/long-parameter-list) - [Data Clumps](https://refactoring.guru/smells/data-clumps) - [Object-Orientation Abusers](https://refactoring.guru/refactoring/smells/oo-abusers) - [Switch Statements](https://refactoring.guru/smells/switch-statements) - [Temporary Field](https://refactoring.guru/smells/temporary-field) - [Refused Bequest](https://refactoring.guru/smells/refused-bequest) - [Alternative Classes with Different Interfaces](https://refactoring.guru/smells/alternative-classes-with-different-interfaces) - [Change Preventers](https://refactoring.guru/refactoring/smells/change-preventers) - [Divergent Change](https://refactoring.guru/smells/divergent-change) - [Shotgun Surgery](https://refactoring.guru/smells/shotgun-surgery) - [Parallel Inheritance Hierarchies](https://refactoring.guru/smells/parallel-inheritance-hierarchies) - [Dispensables](https://refactoring.guru/refactoring/smells/dispensables) - [Comments](https://refactoring.guru/smells/comments) - [Duplicate Code](https://refactoring.guru/smells/duplicate-code) - [Lazy Class](https://refactoring.guru/smells/lazy-class) - [Data Class](https://refactoring.guru/smells/data-class) - [Dead Code](https://refactoring.guru/smells/dead-code) - [Speculative Generality](https://refactoring.guru/smells/speculative-generality) - [Couplers](https://refactoring.guru/refactoring/smells/couplers) - [Feature Envy](https://refactoring.guru/smells/feature-envy) - [Inappropriate Intimacy](https://refactoring.guru/smells/inappropriate-intimacy) - [Message Chains](https://refactoring.guru/smells/message-chains) - [Middle Man](https://refactoring.guru/smells/middle-man) - [Other Smells](https://refactoring.guru/refactoring/smells/other) - [Incomplete Library Class](https://refactoring.guru/smells/incomplete-library-class) - [Refactorings](https://refactoring.guru/refactoring/techniques) - [Composing Methods](https://refactoring.guru/refactoring/techniques/composing-methods) - [Extract Method](https://refactoring.guru/extract-method) - [Inline Method](https://refactoring.guru/inline-method) - [Extract Variable](https://refactoring.guru/extract-variable) - [Inline Temp](https://refactoring.guru/inline-temp) - [Replace Temp with Query](https://refactoring.guru/replace-temp-with-query) - [Split Temporary Variable](https://refactoring.guru/split-temporary-variable) - [Remove Assignments to Parameters](https://refactoring.guru/remove-assignments-to-parameters) - [Replace Method with Method Object](https://refactoring.guru/replace-method-with-method-object) - [Substitute Algorithm](https://refactoring.guru/substitute-algorithm) - [Moving Features between Objects](https://refactoring.guru/refactoring/techniques/moving-features-between-objects) - [Move Method](https://refactoring.guru/move-method) - [Move Field](https://refactoring.guru/move-field) - [Extract Class](https://refactoring.guru/extract-class) - [Inline Class](https://refactoring.guru/inline-class) - [Hide Delegate](https://refactoring.guru/hide-delegate) - [Remove Middle Man](https://refactoring.guru/remove-middle-man) - [Introduce Foreign Method](https://refactoring.guru/introduce-foreign-method) - [Introduce Local Extension](https://refactoring.guru/introduce-local-extension) - [Organizing Data](https://refactoring.guru/refactoring/techniques/organizing-data) - [Self Encapsulate Field](https://refactoring.guru/self-encapsulate-field) - [Replace Data Value with Object](https://refactoring.guru/replace-data-value-with-object) - [Change Value to Reference](https://refactoring.guru/change-value-to-reference) - [Change Reference to Value](https://refactoring.guru/change-reference-to-value) - [Replace Array with Object](https://refactoring.guru/replace-array-with-object) - [Duplicate Observed Data](https://refactoring.guru/duplicate-observed-data) - [Change Unidirectional Association to Bidirectional](https://refactoring.guru/change-unidirectional-association-to-bidirectional) - [Change Bidirectional Association to Unidirectional](https://refactoring.guru/change-bidirectional-association-to-unidirectional) - [Replace Magic Number with Symbolic Constant](https://refactoring.guru/replace-magic-number-with-symbolic-constant) - [Encapsulate Field](https://refactoring.guru/encapsulate-field) - [Encapsulate Collection](https://refactoring.guru/encapsulate-collection) - [Replace Type Code with Class](https://refactoring.guru/replace-type-code-with-class) - [Replace Type Code with Subclasses](https://refactoring.guru/replace-type-code-with-subclasses) - [Replace Type Code with State/Strategy](https://refactoring.guru/replace-type-code-with-state-strategy) - [Replace Subclass with Fields](https://refactoring.guru/replace-subclass-with-fields) - [Simplifying Conditional Expressions](https://refactoring.guru/refactoring/techniques/simplifying-conditional-expressions) - [Decompose Conditional](https://refactoring.guru/decompose-conditional) - [Consolidate Conditional Expression](https://refactoring.guru/consolidate-conditional-expression) - [Consolidate Duplicate Conditional Fragments](https://refactoring.guru/consolidate-duplicate-conditional-fragments) - [Remove Control Flag](https://refactoring.guru/remove-control-flag) - [Replace Nested Conditional with Guard Clauses](https://refactoring.guru/replace-nested-conditional-with-guard-clauses) - [Replace Conditional with Polymorphism](https://refactoring.guru/replace-conditional-with-polymorphism) - [Introduce Null Object](https://refactoring.guru/introduce-null-object) - [Introduce Assertion](https://refactoring.guru/introduce-assertion) - [Simplifying Method Calls](https://refactoring.guru/refactoring/techniques/simplifying-method-calls) - [Rename Method](https://refactoring.guru/rename-method) - [Add Parameter](https://refactoring.guru/add-parameter) - [Remove Parameter](https://refactoring.guru/remove-parameter) - [Separate Query from Modifier](https://refactoring.guru/separate-query-from-modifier) - [Parameterize Method](https://refactoring.guru/parameterize-method) - [Replace Parameter with Explicit Methods](https://refactoring.guru/replace-parameter-with-explicit-methods) - [Preserve Whole Object](https://refactoring.guru/preserve-whole-object) - [Replace Parameter with Method Call](https://refactoring.guru/replace-parameter-with-method-call) - [Introduce Parameter Object](https://refactoring.guru/introduce-parameter-object) - [Remove Setting Method](https://refactoring.guru/remove-setting-method) - [Hide Method](https://refactoring.guru/hide-method) - [Replace Constructor with Factory Method](https://refactoring.guru/replace-constructor-with-factory-method) - [Replace Error Code with Exception](https://refactoring.guru/replace-error-code-with-exception) - [Replace Exception with Test](https://refactoring.guru/replace-exception-with-test) - [Dealing with Generalization](https://refactoring.guru/refactoring/techniques/dealing-with-generalization) - [Pull Up Field](https://refactoring.guru/pull-up-field) - [Pull Up Method](https://refactoring.guru/pull-up-method) - [Pull Up Constructor Body](https://refactoring.guru/pull-up-constructor-body) - [Push Down Method](https://refactoring.guru/push-down-method) - [Push Down Field](https://refactoring.guru/push-down-field) - [Extract Subclass](https://refactoring.guru/extract-subclass) - [Extract Superclass](https://refactoring.guru/extract-superclass) - [Extract Interface](https://refactoring.guru/extract-interface) - [Collapse Hierarchy](https://refactoring.guru/collapse-hierarchy) - [Form Template Method](https://refactoring.guru/form-template-method) - [Replace Inheritance with Delegation](https://refactoring.guru/replace-inheritance-with-delegation) - [Replace Delegation with Inheritance](https://refactoring.guru/replace-delegation-with-inheritance) - [Design Patterns](https://refactoring.guru/design-patterns) - [What is a Pattern](https://refactoring.guru/design-patterns/what-is-pattern) - [What's a design pattern?](https://refactoring.guru/design-patterns/what-is-pattern) - [History of patterns](https://refactoring.guru/design-patterns/history) - [Why should I learn patterns?](https://refactoring.guru/design-patterns/why-learn-patterns) - [Criticism of patterns](https://refactoring.guru/design-patterns/criticism) - [Classification of patterns](https://refactoring.guru/design-patterns/classification) - [Catalog](https://refactoring.guru/design-patterns/catalog) - [Creational Patterns](https://refactoring.guru/design-patterns/creational-patterns) - [Factory Method](https://refactoring.guru/design-patterns/factory-method) - [Abstract Factory](https://refactoring.guru/design-patterns/abstract-factory) - [Builder](https://refactoring.guru/design-patterns/builder) - [Prototype](https://refactoring.guru/design-patterns/prototype) - [Singleton](https://refactoring.guru/design-patterns/singleton) - [Structural Patterns](https://refactoring.guru/design-patterns/structural-patterns) - [Adapter](https://refactoring.guru/design-patterns/adapter) - [Bridge](https://refactoring.guru/design-patterns/bridge) - [Composite](https://refactoring.guru/design-patterns/composite) - [Decorator](https://refactoring.guru/design-patterns/decorator) - [Facade](https://refactoring.guru/design-patterns/facade) - [Flyweight](https://refactoring.guru/design-patterns/flyweight) - [Proxy](https://refactoring.guru/design-patterns/proxy) - [Behavioral Patterns](https://refactoring.guru/design-patterns/behavioral-patterns) - [Chain of Responsibility](https://refactoring.guru/design-patterns/chain-of-responsibility) - [Command](https://refactoring.guru/design-patterns/command) - [Iterator](https://refactoring.guru/design-patterns/iterator) - [Mediator](https://refactoring.guru/design-patterns/mediator) - [Memento](https://refactoring.guru/design-patterns/memento) - [Observer](https://refactoring.guru/design-patterns/observer) - [State](https://refactoring.guru/design-patterns/state) - [Strategy](https://refactoring.guru/design-patterns/strategy) - [Template Method](https://refactoring.guru/design-patterns/template-method) - [Visitor](https://refactoring.guru/design-patterns/visitor) - [Code Examples](https://refactoring.guru/design-patterns/examples) - [C\#](https://refactoring.guru/design-patterns/csharp) - [C++](https://refactoring.guru/design-patterns/cpp) - [Go](https://refactoring.guru/design-patterns/go) - [Java](https://refactoring.guru/design-patterns/java) - [PHP](https://refactoring.guru/design-patterns/php) - [Python](https://refactoring.guru/design-patterns/python) - [Ruby](https://refactoring.guru/design-patterns/ruby) - [Rust](https://refactoring.guru/design-patterns/rust) - [Swift](https://refactoring.guru/design-patterns/swift) - [TypeScript](https://refactoring.guru/design-patterns/typescript) [Sign in](https://refactoring.guru/login "Sign in") [Contact us](https://feedback.refactoring.guru/ "Contact us") [![Refactoring.Guru](https://refactoring.guru/images/content-public/logos/logo-new-mobile.png?id=ea18aa9b032eaa92835ed6d472b03b4a)](https://refactoring.guru/) [Shop Now\!](https://refactoring.guru/store) - English [English](https://refactoring.guru/design-patterns/command "English") [Español](https://refactoring.guru/es/design-patterns/command "Español") [Français](https://refactoring.guru/fr/design-patterns/command "Français") [æ—„æœŹèȘž](https://refactoring.guru/ja/design-patterns/command "æ—„æœŹèȘž") [한ꔭ얎](https://refactoring.guru/ko/design-patterns/command "한ꔭ얎") [Polski](https://refactoring.guru/pl/design-patterns/command "Polski") [PortuguĂȘs Brasileiro](https://refactoring.guru/pt-br/design-patterns/command "PortuguĂȘs Brasileiro") [РуссĐșĐžĐč](https://refactoring.guru/ru/design-patterns/command "РуссĐșĐžĐč") [ĐŁĐșŃ€Đ°Ń—ĐœŃŃŒĐșа](https://refactoring.guru/uk/design-patterns/command "ĐŁĐșŃ€Đ°Ń—ĐœŃŃŒĐșа") [äž­æ–‡](https://refactoringguru.cn/design-patterns/command "äž­æ–‡") - [Contact us](https://feedback.refactoring.guru/?show_feedback_form_private=true "Contact us") - [Sign in](https://refactoring.guru/login "Sign in") - [Home](https://refactoring.guru/) - [Refactoring](https://refactoring.guru/refactoring) - [Design Patterns](https://refactoring.guru/design-patterns) - [Premium Content](https://refactoring.guru/store) - [Git Course](https://gitbybit.com/) - [Forum](https://refactoring.userecho.com/) - [Contact us](https://refactoring.userecho.com/) 2014-2026 [Refactoring.Guru](https://refactoring.guru/). All rights reserved. Illustrations by [Dmitry Zhart](http://zhart.us/) - [Terms & Conditions](https://refactoring.guru/terms) - [Privacy Policy](https://refactoring.guru/privacy-policy) - [Content Usage Policy](https://refactoring.guru/content-usage-policy) - [About us](https://refactoring.guru/site-about) **Ukrainian office:** ![Organization address](https://refactoring.guru/images/content-public/icons/fa-building.svg?id=07fc08377514bd473225f627b40a1608) FOP Olga Skobeleva Abolmasova 7 Kyiv, Ukraine, 02002 Email: support@refactoring.guru **Spanish office:** ![Organization address](https://refactoring.guru/images/content-public/icons/fa-building.svg?id=07fc08377514bd473225f627b40a1608) Oleksandr Shvets Avda Pamplona 64 Pamplona, Spain, 31009 Email: support@refactoring.guru
Readable Markdown
Also known as: Action, Transaction ## Intent **Command** is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations. ![Command design pattern](https://refactoring.guru/images/patterns/content/command/command-en.png?id=80fbadc666cf3b9b1958c546d2746ca4) ## Problem Imagine that you’re working on a new text-editor app. Your current task is to create a toolbar with a bunch of buttons for various operations of the editor. You created a very neat `Button` class that can be used for buttons on the toolbar, as well as for generic buttons in various dialogs. ![Problem solved by the Command pattern](https://refactoring.guru/images/patterns/diagrams/command/problem1.png?id=84189315a0e8d91da262792979005ab4) All buttons of the app are derived from the same class. While all of these buttons look similar, they’re all supposed to do different things. Where would you put the code for the various click handlers of these buttons? The simplest solution is to create tons of subclasses for each place where the button is used. These subclasses would contain the code that would have to be executed on a button click. ![Lots of button subclasses](https://refactoring.guru/images/patterns/diagrams/command/problem2.png?id=f0e33da1842b3a3ee3b4857de0b6ec93) Lots of button subclasses. What can go wrong? Before long, you realize that this approach is deeply flawed. First, you have an enormous number of subclasses, and that would be okay if you weren’t risking breaking the code in these subclasses each time you modify the base `Button` class. Put simply, your GUI code has become awkwardly dependent on the volatile code of the business logic. ![Several classes implement the same functionality](https://refactoring.guru/images/patterns/diagrams/command/problem3-en.png?id=1fbd56ae7ba3e3dfac45cfa2de6db450) Several classes implement the same functionality. And here’s the ugliest part. Some operations, such as copying/pasting text, would need to be invoked from multiple places. For example, a user could click a small “Copy” button on the toolbar, or copy something via the context menu, or just hit `Ctrl+C` on the keyboard. Initially, when our app only had the toolbar, it was okay to place the implementation of various operations into the button subclasses. In other words, having the code for copying text inside the `CopyButton` subclass was fine. But then, when you implement context menus, shortcuts, and other stuff, you have to either duplicate the operation’s code in many classes or make menus dependent on buttons, which is an even worse option. ## Solution Good software design is often based on the *principle of separation of concerns*, which usually results in breaking an app into layers. The most common example: a layer for the graphical user interface and another layer for the business logic. The GUI layer is responsible for rendering a beautiful picture on the screen, capturing any input and showing results of what the user and the app are doing. However, when it comes to doing something important, like calculating the trajectory of the moon or composing an annual report, the GUI layer delegates the work to the underlying layer of business logic. In the code it might look like this: a GUI object calls a method of a business logic object, passing it some arguments. This process is usually described as one object sending another a *request*. ![The GUI layer may access the business logic layer directly](https://refactoring.guru/images/patterns/diagrams/command/solution1-en.png?id=ec37db1713fe2c1a9318886590667cfb) The GUI objects may access the business logic objects directly. The Command pattern suggests that GUI objects shouldn’t send these requests directly. Instead, you should extract all of the request details, such as the object being called, the name of the method and the list of arguments into a separate *command* class with a single method that triggers this request. Command objects serve as links between various GUI and business logic objects. From now on, the GUI object doesn’t need to know what business logic object will receive the request and how it’ll be processed. The GUI object just triggers the command, which handles all the details. ![Accessing the business logic layer via a command.](https://refactoring.guru/images/patterns/diagrams/command/solution2-en.png?id=63bcac5cde2ec536c3329eff4c385839) Accessing the business logic layer via a command. The next step is to make your commands implement the same interface. Usually it has just a single execution method that takes no parameters. This interface lets you use various commands with the same request sender, without coupling it to concrete classes of commands. As a bonus, now you can switch command objects linked to the sender, effectively changing the sender’s behavior at runtime. You might have noticed one missing piece of the puzzle, which is the request parameters. A GUI object might have supplied the business-layer object with some parameters. Since the command execution method doesn’t have any parameters, how would we pass the request details to the receiver? It turns out the command should be either pre-configured with this data, or capable of getting it on its own. ![The GUI objects delegate the work to commands](https://refactoring.guru/images/patterns/diagrams/command/solution3-en.png?id=c92f6874b95de46b041499d41234b00b) The GUI objects delegate the work to commands. Let’s get back to our text editor. After we apply the Command pattern, we no longer need all those button subclasses to implement various click behaviors. It’s enough to put a single field into the base `Button` class that stores a reference to a command object and make the button execute that command on a click. You’ll implement a bunch of command classes for every possible operation and link them with particular buttons, depending on the buttons’ intended behavior. Other GUI elements, such as menus, shortcuts or entire dialogs, can be implemented in the same way. They’ll be linked to a command which gets executed when a user interacts with the GUI element. As you’ve probably guessed by now, the elements related to the same operations will be linked to the same commands, preventing any code duplication. As a result, commands become a convenient middle layer that reduces coupling between the GUI and business logic layers. And that’s only a fraction of the benefits that the Command pattern can offer\! ## Real-World Analogy ![Making an order in a restaurant](https://refactoring.guru/images/patterns/content/command/command-comic-1.png?id=551df832f445080976f3116e0dc120c9) Making an order in a restaurant. After a long walk through the city, you get to a nice restaurant and sit at the table by the window. A friendly waiter approaches you and quickly takes your order, writing it down on a piece of paper. The waiter goes to the kitchen and sticks the order on the wall. After a while, the order gets to the chef, who reads it and cooks the meal accordingly. The cook places the meal on a tray along with the order. The waiter discovers the tray, checks the order to make sure everything is as you wanted it, and brings everything to your table. The paper order serves as a command. It remains in a queue until the chef is ready to serve it. The order contains all the relevant information required to cook the meal. It allows the chef to start cooking right away instead of running around clarifying the order details from you directly. ## Structure 1. The **Sender** class (aka *invoker*) is responsible for initiating requests. This class must have a field for storing a reference to a command object. The sender triggers that command instead of sending the request directly to the receiver. Note that the sender isn’t responsible for creating the command object. Usually, it gets a pre-created command from the client via the constructor. 2. The **Command** interface usually declares just a single method for executing the command. 3. **Concrete Commands** implement various kinds of requests. A concrete command isn’t supposed to perform the work on its own, but rather to pass the call to one of the business logic objects. However, for the sake of simplifying the code, these classes can be merged. Parameters required to execute a method on a receiving object can be declared as fields in the concrete command. You can make command objects immutable by only allowing the initialization of these fields via the constructor. 4. The **Receiver** class contains some business logic. Almost any object may act as a receiver. Most commands only handle the details of how a request is passed to the receiver, while the receiver itself does the actual work. 5. The **Client** creates and configures concrete command objects. The client must pass all of the request parameters, including a receiver instance, into the command’s constructor. After that, the resulting command may be associated with one or multiple senders. ## Pseudocode In this example, the **Command** pattern helps to track the history of executed operations and makes it possible to revert an operation if needed. ![Structure of the Command pattern example](https://refactoring.guru/images/patterns/diagrams/command/example.png?id=1f42c8395fe54d0e409026b91881e2a0) Undoable operations in a text editor. Commands which result in changing the state of the editor (e.g., cutting and pasting) make a backup copy of the editor’s state before executing an operation associated with the command. After a command is executed, it’s placed into the command history (a stack of command objects) along with the backup copy of the editor’s state at that point. Later, if the user needs to revert an operation, the app can take the most recent command from the history, read the associated backup of the editor’s state, and restore it. The client code (GUI elements, command history, etc.) isn’t coupled to concrete command classes because it works with commands via the command interface. This approach lets you introduce new commands into the app without breaking any existing code. ``` // The base command class defines the common interface for all // concrete commands. abstract class Command is protected field app: Application protected field editor: Editor protected field backup: text constructor Command(app: Application, editor: Editor) is this.app = app this.editor = editor // Make a backup of the editor's state. method saveBackup() is backup = editor.text // Restore the editor's state. method undo() is editor.text = backup // The execution method is declared abstract to force all // concrete commands to provide their own implementations. // The method must return true or false depending on whether // the command changes the editor's state. abstract method execute() // The concrete commands go here. class CopyCommand extends Command is // The copy command isn't saved to the history since it // doesn't change the editor's state. method execute() is app.clipboard = editor.getSelection() return false class CutCommand extends Command is // The cut command does change the editor's state, therefore // it must be saved to the history. And it'll be saved as // long as the method returns true. method execute() is saveBackup() app.clipboard = editor.getSelection() editor.deleteSelection() return true class PasteCommand extends Command is method execute() is saveBackup() editor.replaceSelection(app.clipboard) return true // The undo operation is also a command. class UndoCommand extends Command is method execute() is app.undo() return false // The global command history is just a stack. class CommandHistory is private field history: array of Command // Last in... method push(c: Command) is // Push the command to the end of the history array. // ...first out method pop():Command is // Get the most recent command from the history. // The editor class has actual text editing operations. It plays // the role of a receiver: all commands end up delegating // execution to the editor's methods. class Editor is field text: string method getSelection() is // Return selected text. method deleteSelection() is // Delete selected text. method replaceSelection(text) is // Insert the clipboard's contents at the current // position. // The application class sets up object relations. It acts as a // sender: when something needs to be done, it creates a command // object and executes it. class Application is field clipboard: string field editors: array of Editors field activeEditor: Editor field history: CommandHistory // The code which assigns commands to UI objects may look // like this. method createUI() is // ... copy = function() { executeCommand( new CopyCommand(this, activeEditor)) } copyButton.setCommand(copy) shortcuts.onKeyPress("Ctrl+C", copy) cut = function() { executeCommand( new CutCommand(this, activeEditor)) } cutButton.setCommand(cut) shortcuts.onKeyPress("Ctrl+X", cut) paste = function() { executeCommand( new PasteCommand(this, activeEditor)) } pasteButton.setCommand(paste) shortcuts.onKeyPress("Ctrl+V", paste) undo = function() { executeCommand( new UndoCommand(this, activeEditor)) } undoButton.setCommand(undo) shortcuts.onKeyPress("Ctrl+Z", undo) // Execute a command and check whether it has to be added to // the history. method executeCommand(command) is if (command.execute()) history.push(command) // Take the most recent command from the history and run its // undo method. Note that we don't know the class of that // command. But we don't have to, since the command knows // how to undo its own action. method undo() is command = history.pop() if (command != null) command.undo() ``` ## Applicability Use the Command pattern when you want to parameterize objects with operations. The Command pattern can turn a specific method call into a stand-alone object. This change opens up a lot of interesting uses: you can pass commands as method arguments, store them inside other objects, switch linked commands at runtime, etc. Here’s an example: you’re developing a GUI component such as a context menu, and you want your users to be able to configure menu items that trigger operations when an end user clicks an item. Use the Command pattern when you want to queue operations, schedule their execution, or execute them remotely. As with any other object, a command can be serialized, which means converting it to a string that can be easily written to a file or a database. Later, the string can be restored as the initial command object. Thus, you can delay and schedule command execution. But there’s even more! In the same way, you can queue, log or send commands over the network. Use the Command pattern when you want to implement reversible operations. Although there are many ways to implement undo/redo, the Command pattern is perhaps the most popular of all. To be able to revert operations, you need to implement the history of performed operations. The command history is a stack that contains all executed command objects along with related backups of the application’s state. This method has two drawbacks. First, it isn’t that easy to save an application’s state because some of it can be private. This problem can be mitigated with the [Memento](https://refactoring.guru/design-patterns/memento) pattern. Second, the state backups may consume quite a lot of RAM. Therefore, sometimes you can resort to an alternative implementation: instead of restoring the past state, the command performs the inverse operation. The reverse operation also has a price: it may turn out to be hard or even impossible to implement. ## How to Implement 1. Declare the command interface with a single execution method. 2. Start extracting requests into concrete command classes that implement the command interface. Each class must have a set of fields for storing the request arguments along with a reference to the actual receiver object. All these values must be initialized via the command’s constructor. 3. Identify classes that will act as *senders*. Add the fields for storing commands into these classes. Senders should communicate with their commands only via the command interface. Senders usually don’t create command objects on their own, but rather get them from the client code. 4. Change the senders so they execute the command instead of sending a request to the receiver directly. 5. The client should initialize objects in the following order: - Create receivers. - Create commands, and associate them with receivers if needed. - Create senders, and associate them with specific commands. ## Pros and Cons - *Single Responsibility Principle*. You can decouple classes that invoke operations from classes that perform these operations. - *Open/Closed Principle*. You can introduce new commands into the app without breaking existing client code. - You can implement undo/redo. - You can implement deferred execution of operations. - You can assemble a set of simple commands into a complex one. - The code may become more complicated since you’re introducing a whole new layer between senders and receivers. ## Relations with Other Patterns - [Chain of Responsibility](https://refactoring.guru/design-patterns/chain-of-responsibility), [Command](https://refactoring.guru/design-patterns/command), [Mediator](https://refactoring.guru/design-patterns/mediator) and [Observer](https://refactoring.guru/design-patterns/observer) address various ways of connecting senders and receivers of requests: - *Chain of Responsibility* passes a request sequentially along a dynamic chain of potential receivers until one of them handles it. - *Command* establishes unidirectional connections between senders and receivers. - *Mediator* eliminates direct connections between senders and receivers, forcing them to communicate indirectly via a mediator object. - *Observer* lets receivers dynamically subscribe to and unsubscribe from receiving requests. - Handlers in [Chain of Responsibility](https://refactoring.guru/design-patterns/chain-of-responsibility) can be implemented as [Commands](https://refactoring.guru/design-patterns/command). In this case, you can execute a lot of different operations over the same context object, represented by a request. However, there’s another approach, where the request itself is a *Command* object. In this case, you can execute the same operation in a series of different contexts linked into a chain. - You can use [Command](https://refactoring.guru/design-patterns/command) and [Memento](https://refactoring.guru/design-patterns/memento) together when implementing “undo”. In this case, commands are responsible for performing various operations over a target object, while mementos save the state of that object just before a command gets executed. - [Command](https://refactoring.guru/design-patterns/command) and [Strategy](https://refactoring.guru/design-patterns/strategy) may look similar because you can use both to parameterize an object with some action. However, they have very different intents. - You can use *Command* to convert any operation into an object. The operation’s parameters become fields of that object. The conversion lets you defer execution of the operation, queue it, store the history of commands, send commands to remote services, etc. - On the other hand, *Strategy* usually describes different ways of doing the same thing, letting you swap these algorithms within a single context class. - [Prototype](https://refactoring.guru/design-patterns/prototype) can help when you need to save copies of [Commands](https://refactoring.guru/design-patterns/command) into history. - You can treat [Visitor](https://refactoring.guru/design-patterns/visitor) as a powerful version of the [Command](https://refactoring.guru/design-patterns/command) pattern. Its objects can execute operations over various objects of different classes.
Shard167 (laksa)
Root Hash9248089470450236767
Unparsed URLguru,refactoring!/design-patterns/command s443