In an attempt to solidify my understanding of the command pattern, I decided to write a calculator application that utilised it.
After making some progress, I realised that my choice of application may not have been the ideal choice.
I have the following components:
View.xml
This is the user interface of the calculator, and is equivalent to the “client” in diagram. This is my view layer.
Controller.cs
This is the equivalent to the “invoker” in the diagram, this holds the commands, and calls execute on them. This is my controller layer
Model.cs
This is the equivalent to the “receiver” on the diagram.
commandOne.cs, comandTwo.cs, commandMinus.cs...... etc
These are my concrete commands , that define a binding between an action and the model.
As well as executing the commands, the controller also mains a queue of commands for the purposes of undo and redo.
In applying the command pattern to a calculator, I realised that execution of the commands is deferred until the entire expression has been created and equals has been pressed. I therefore set about recoding the sequence of button presses in the model layer before realising that I already had a container storing these in the form of the undo/redo queue in the controller.
Therefore, my question is, should I pass my controller/invoker to the model layer when the expression has been completed so that the commands in the queue can be run sequentially to calculate the result.
Or should I persist a similar queue in the model layer for the purposes of evaluating the expression when the equals button has been pressed.
View
nor yourController
should really have any knowledge of your underlying application logic (in this case, your calculator logic). AView
is for layout/colours/fonts/etc. AController
is for Interactivity logic (e.g. enabling/disabling buttons, querying the view for data, or sending data to the view). As far as MVC is concerned, theModel
(which may be a slightly misleading term) is a catch-all term meaning "the rest of your application logic".