Design Pattern Download: The Command Pattern
The Command pattern is a Behavioral Pattern used in software engineering when we want to separate our client request from the actual client layer so that the code doesn’t need to be repeated and and can live in its own object.
Example
We have a website which has a user profile page, the users have a Key value store in our server of certain personal info items such as name, email and birthday we want to enable users to update that info on the settings page. Users can save info by entering it into a text box and hitting the save button or they can use a shortcut keystroke defined in our system. The saving functionality itself is identical no matter what way the user saved so instead of duplicating the same code in the shortcut class and button class, we create a Save Command which both save options can use to create and execute a save. We could also use this to offload operations, so we can create a stack of saves and then when the user exits the page, we can send them all in a batch instead of invoking the save every time it is done.
When to use the Command?
- When you want to parametrize a request into its own object to decouple system layers.
- When you want delay and schedule operations for a later time, to enable batching or allow for easy undos without having to talk to backend service.
What is the Command Pattern composed of?
- The Command ( the object the takes in the information needed to execute)
- The Client(s) (the points in where we want to create and execute the commands)
Implementation
The Command
The Client
Now we can call the commands at a later time than the user actually saved the details and we can use the same simple process of adding a command to the list instead of writing duplicate server interfaces for each of the saving methods.
Saving name:jack to system
Saving name:jill to system