Search code examples
design-patternscommand-pattern

Command pattern is the command a single instance


Does the definition for the command pattern tells if the command should be reusable. I mean are you supposed to create a new instance every time you want to call the execute-method or can you create a single instance of the command and call execute multiple times with different parameters?

Being on the .net platform, I can see that commands in WPF are only created once, not sure though that's the answer.

Perhaps another way to look at it, is a command disallowed to hold state, like a ddd-service, if so having a single instance would be fine.

If this is not part of the patterns definition, does any "best practices" exists?


Solution

  • Command objects in the GoF pattern are most certainly reusable. The most common case for reuse is in Commands that support an undo operation. An Invoker can call execute() to perform an action and later call undo() to roll back that action. The Invoker can execute() and undo() innumerable times at will.

    It is critical to the pattern that the Invoker has no knowledge of how the Command executes, including any arguments necessary for execution (or undo). Arguments must be encapsulated within the Command object, meaning they can be passed when the Command is instantiated, but not when it is executed.

    It is obvious then, that the Invoker would never instantiate a Command itself because the whole point is to decouple the Invoker from execution details by providing a black box that just works. More on that topic here: https://stackoverflow.com/a/52877064/1371329.

    are you supposed to create a new instance every time you want to call the execute-method

    No, you are only supposed to create a new instance when you want the execute() method to be called with different parameters. The Command holds these parameters as its state so that the Invoker doesn't have to know about them.

    Think of it like clicking a button. You don't get to pass arguments to the button. The button executes an action that may have arguments behind the UI, but you don't pass anything in order to click the button. You are the Invoker. The button is the Command. The UI that created the button and parameterized it with some action is the Client. The Client decouples the Invoker from the action through the Command interface.