The whole thing start with a command interface which looks like this
The only thing you need in a command is execute and undo. With that you can even make a redo. Really? Really, I'll show you the idea of the history implementation.
To make the whole thing work you need to encapsulate everything needed to execute the command in your command object, that is of great importance.
For the implementation I used a LinkedList as it was the simplest way I found for this. Of course you can implement as well some ring buffer structure using plain arrays, but I did not had the nerve for this. I'm sure you have.
Ok let's start with the basics. First of all we need to execute the command like this
That wasn't too hard, but to be able to undo it, we need to hold that command in a data structure, a linked list in my case.
Oh wait what if I undo when the list is empty? Yes it fails, so we need some guards to protect it.
That looks not that bad and it works already. But let's improve it a little more. For example does this implementation not limit the number of commands in our history, so let's introduce a size.
And now we have to improve the execute method with this size information, be dropping the first command if we hit the capacity of our history.
A redo would be cool and it turns out to be very simple. We need a linked list for book-keeping.
Then we have to store all undoed commands in that redoCommands list.
Now we are prepared for the redo method
One small problem we have to solve, what if we did undo 2 times and then call execute and after that call redo? Yeah it will end up in redo commands which actually should be cleared. So let's clear the redo command list on execute. This is not that easy as the redo itself call execute to have the command book-keeping for free. The easiest way is to have an internal execute which is called by execute and redo and only execute clears the redo commands list.
And to make it a simple copy&past task to take this into your project here the things you need