The command pattern in Go
This is a continuation of the common design patterns I found in my old code series, which I started in a previous post.
The command pattern is a design pattern that encapsulates an action or request as an object that can be parameterized. And it’s commonly associated with terms like receiver, command, invoker and client.
Usually, the invoker doesn’t know anything about the implementation details of the command or receiver, it just knows the command interface and its only responsibility is to invoke the command and optionally do bookkeeping of commands.
The command is the object that knows about the receiver and its responsibility is to execute methods on the receiver.
Go’s exec package is an example of this pattern:
Or the net/http package:
Though, it’s not straightforward to see which is the invoker and receiver.
But take the following example:
It’s easy to see that:
Pingeris the invoker
Pingis the receiver
PingCmdis the command
What this pattern essentially allows us is to decouple the action/request logic from the execution. This can be useful in a variety of situations:
- Undo interactions
- Remote execution
- Parallel processing
- Micro-service architectures
- Task queues
For more design pattern examples, please checkout rolandjitsu/go-design-patterns.
If you find this post helpful, please consider sponsoring.Sponsor