The Command Pattern
Learn about the Command pattern and learn its implementation using a real-world example.
We'll cover the following
Overview
When we think about class responsibilities, we can sometimes distinguish passive classes that hold objects and maintain an internal state, but don’t initiate very much, and “active” classes that reach out into other objects to take action and do things. This is not a very crisp distinction, but it can help separate the relatively passive Observer and the more active Command design patterns. An Observer is notified that something changed. A Commander, on the other hand, will be active, making state changes in other objects. We can combine the two aspects, and that’s one of the beauties of talking about a software architecture by describing the various patterns that apply to a class or a relationship among classes.
The Command pattern generally involves a hierarchy of classes that each do something. A Core class can create a command (or a sequence of commands) to carry out actions.
In a way, it’s a kind of meta-programming: by creating Command objects that contain a bunch of statements, the design has a higher-level language of Command objects.
Here’s a UML diagram showing a Core object and a collection of Commands:
Get hands-on with 1200+ tech skills courses.