The Command Pattern
What?
The Command Pattern allows us to group operations in an object which can be passed around and invoked on demand.
Why?
Useful for cases where we wish to pass an action around our system, store it, defer it, or queue it.
How?
We start with a Receiver. This is one of our business objects. We'll use a User
in this example, and it is the object on which our command is going to operate.
class User
def send_welcome_email
# ...
end
def apply_introductory_discount
# ...
end
end
The Command
class is the lowest level building block of the pattern.
class Command
# This is to convey our intent that subclasses should implement this method.
def execute
raise NotImplementedError
end
end
And now we can implement GreetUserCommand
, which we can pass on or store.
class GreetUserCommand < Command
def initialize(user)
@user = user
end
def execute
@user.send_welcome_email
@user.apply_introductory_discount
end
end