Today I wonder how simple and elegant I was able to implement the command pattern with Swift 2. I started as usual with a bunch of classes until I realised that Swift closures provide exactly what is needed to implement the command objects. This makes the implementation very simple and elegant!
The intent of the command pattern is to encapsulate a piece of code as an object, thereby letting you store code and execute it later. The executor of the command objects and the command objects are completely decoupled from each other.
Want to try out the code yourself? Checkout my design pattern git repository and open CommandPattern.playground.
Structure and Collaboration
Four terms are always associated with the command pattern: command, receiver, invoker and client. A command object knows about receiver and invokes a method of the receiver. Values for parameters of the receiver method are stored in the command. The receiver then does the work. An invoker object knows how to execute a command, and optionally does bookkeeping about the command execution. The invoker does not know anything about a concrete command, it knows only about command interface. Both an invoker object and several command objects are held by a client object. The client decides which commands to execute at which points. To execute a command, it passes the command object to the invoker object.
Implementation