Introduction to the Command Pattern
Introduction to the Command Pattern
Welcome back! In the previous lessons, we explored various behavioral patterns like the Strategy and Observer Patterns. This time, we'll dive into the Command Pattern, a powerful technique that encapsulates a request as an object, thereby allowing for the parameterization and queuing of requests.
What You'll Learn
In this lesson, you will discover how to implement the Command Pattern in Go, which will enable you to decouple the sender and receiver of a request. Specifically, you'll learn to:
- Define a Command interface: Create a blueprint for executing commands.
- Implement Concrete Commands: Learn to encapsulate specific actions (like turning a light on or off).
- Use an Invoker: Understand how to create an invoker to hold and execute commands.
Let's take a peek at an example, which we'll break down step by step:
We start by defining a Command interface with an Execute method:
Next, we create concrete commands that implement the Command interface. The LightOnCommand and LightOffCommand structs represent turning a light on and off, respectively, and implement the Execute method to print the corresponding message when executed:
We then create an invoker, Button, that holds a command and triggers it when needed. The Press method executes the command stored in the invoker. Therefore if the invoker holds the LightOnCommand, pressing the button will turn the light on:
Finally, we demonstrate how to use the Command Pattern in the main function by creating concrete commands, setting them on the invoker, and triggering them using the invoker:
As you see in the output comments, the Command Pattern allows us to encapsulate actions as objects, making it easy to parameterize and execute them.
Let's break down the key components of the Command Pattern:
- Command: This interface defines the method that concrete commands must implement. In our example, the
Executemethod is used to trigger the command. - Concrete Commands: These are the specific commands that encapsulate actions. In our example,
LightOnCommandandLightOffCommandare concrete commands that turn the light on and off, respectively. - Invoker: The
Buttonstruct acts as an invoker that holds a command and triggers it when needed. ThePressmethod executes the command. - Client Code: The
mainfunction demonstrates how to create concrete commands, set them on the invoker, and trigger them using the invoker.
