Fast undo/redo with memento/command pattern?

前端 未结 2 1068
感动是毒
感动是毒 2020-12-28 23:13

I\'m writing a painting/graphics Java application for a mobile phone (so memory is limited). The application state is essentially three 1000x500 bitmaps (i.e. layers of a pa

相关标签:
2条回答
  • 2020-12-28 23:51

    There is a third common method of handling undo. That is to store the differences between the two states within the Undo object. You can do this as actual differences (i.e. as which pixels have changed and what they changed to) but that is probably nearly as wasteful of memory as storing the bitmap at every stage.

    Alternatively you can use the command pattern approach, but instead of re-running the commands when you undo, you store the inverse of the command - i.e. if the user increased the red value by ten, then the undo command is to decrease it by ten. To undo you simply execute the inverse command. Some commands are hard to find an inverse for, such as "convert to black and white" but by mixing an underlying bitmap with a number of filters which are turned on or off by command you can probably do it.

    As yet another suggestion, use the command approach you mentioned but keep a bitmap for the previous step. When the user does undo immediately display the cached bitmap from the previous (n-1) step and then start calculating the bitmap for n-2 so that you are ready for when he presses undo again.

    0 讨论(0)
  • 2020-12-28 23:52

    About your Use the command pattern point: Starting from the initial state and again executing Commands are not needed at all. Each Command class should represent a small user action and should have mechanism to undo what it does in its execute() method, if undo operation is to be supported. We maintain a stack of ***Command objects. When user undoes something, a Command object is popped out from the stack and its undo() method gets called.

    I do not see any motivation for using memento pattern in your case as the undo actions will be in FIFO order. User is not allowed to undo actions as he pleases, I guess.

    0 讨论(0)
提交回复
热议问题