1 of 12

Command Pattern

Margus Luik

2 of 12

Command Pattern

Intent

Encapsulate a request as an object, thereby letting users parameterize clients with different requests, queue or log requests, and support undoable operations.

  • Design Patterns: Elements of Reusable Object-Oriented Software, p263

3 of 12

Command Pattern

Intent of the pattern:

Encapsulate a request as an object, thereby letting users parameterize clients with different requests, queue or log requests, and support undoable operations.

In other words:

Turn a action into data.

4 of 12

Command Pattern

5 of 12

Command Pattern

Characteristics

Function calls become:

  • Easy to store
  • Easy to reuse
  • Delayed if necessary
  • Configurable during runtime

6 of 12

Command Pattern

Potential applications:

  • Store, queue, reuse, log and execute requests at different times.
  • Great for managing input (rebinding)
  • Decouple in game entities from players/AI
  • Support undo/redo
  • Support replays
  • Support time rewind mechanics

7 of 12

Example

8 of 12

Command Pattern

9 of 12

Example

What parts might be:

  • Commands
  • Clients
  • Receiver
  • Invoker

10 of 12

Example

11 of 12

Example

12 of 12

For the next week

  • Read Command chapter from Game Programming Patterns http://www.gameprogrammingpatterns.com/command.html
  • Complete tasks MoveCommand and SwitchCommand