The Command Pattern
- 3 minsThe last couple of weeks I’ve been working on an internal Rails project and to say that I’ve been learning a lot it would probably be an understatement. One of the things I’ve noticed though is the frequent use and emphasis on Design Patterns.
One of the design patterns I’ve seen often is the Command Pattern.
Definition: “The Command Pattern is a behavioural design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time.”
In Ruby a lot of patterns are not so easy to notice because of the dynamic nature of the language. The “switch” example on the Wikipedia page is an easy one to understand so I’ll implement it in Ruby.
The “Invoker” class:
The “Receiver” class:
The “Command” classes:
The “Client” class
Putting it together:
The “Invoker” class takes the command objects and is responsible for invoking them when needed. The “Command” objects take a “Receiver” object and invoke a method which is specific to that receiver. The “Client” is responsible for bringing those together and is generally where the decision is made on when and how a command is to be executed. Typically the Client object (HouseLight
) passes the Command object (FlipUpCommand
) to the Invoker object (Switch
) which then executes the command.
The reason why in Ruby is harder to see this sort of pattern is because you can dump the “Invoker” object and let the magic of Duck Typing do the rest:
There are several benefits when applying this pattern. For one testing becomes much easier since you can isolate each class and test it with ease since there’s no real dependencies. Also if you decide to use the light and switch elsewhere then it’s pretty easy. Creating extra actions or various switches that do different things should also be easy based on the above.