Answer the question
In order to leave comments, you need to log in
How can I rollback and redo OOP?
echo $calculate->init(20).
->compute('+', 2)
->replay();
->undo();
->getResult();
Answer the question
In order to leave comments, you need to log in
In this form, you can implement it using the stack.
At the very beginning, put the initial value in the field
When calling compute - push the operation and value onto the stack
When calling replay - push the operation and value from the top of the stack onto the stack
When calling undo - remove the pair from the top of the stack When
calling getResult - apply all operations to the saved initial meaning
rollback from which method to which? the easiest way is to keep your own clone and, in case of a rollback, return it.
2 main approaches to rollback implementation:
1. instead of calculations, at each step, simply add or remove the description of operations (sometimes ordinary closures are fine) to a special array, perform real calculations at the moment when the result is requested
2. each step of calculations saves the previous value in a special array , respectively, rollback is getting this value and deleting the last element in the array (if redo is not needed)
Both approaches have their pros and cons, the second approach is more convenient for a simple calculator, but the first one is more convenient for an editor of a complex document.
It is also possible to combine both approaches to optimize resources.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question