[Design Pattern in C++] Command Pattern
Design Pattern in C++ is a series of Heron’s blog posts that shares C++ code examples of each design pattern. You can find all code at this Github repo. I don’t explain the details of each pattern in these posts, please refer to other resources if that’s what you’re looking for.
Definition
Command Pattern encapsulate all information needed to perform an action into a single method. Different implements can override the method differently and the callers are unaware of the implementations.
Code
Command
is an interface that exposes Execute()
, implemented by AttackCommand
and DefenseCommand
. Game
is the caller of different Command
implementations and is unaware how each command is handled as all of them expose the same interface. As a result, Game
can easily map different buttons to execute different commands.
command.h
attack_command.h
DefenseCommand
is similar to AttackCommand
so I am skipping it here.
game.h
game.cc
main.cc
Note
I noticed two properties about Command Pattern:
- “Commands are an object-oriented replacement for callbacks.” With Command Pattern, we can implement a flow that triggers a method — say
Execute()
- when a target event happens.Execute()
then plays the same role as callbacks. - Command Pattern enables us to ‘undo’ an action. To implement ‘undo’, (1) Other than
Execute()
, each command object should also implementUndo()
which does the action to undo anExecute()
, then (2) We push the executed Command objects into a stack. When the caller wants to ‘undo’, we pop one Command object from the stack and call itsUndo()
.
Full Code
Reference
Follow me on Facebook.