Monday, February 23, 2009

Command Pattern - Undo and Command Stack

As requested, here's a demo of the command pattern in action. This example shows how to use the Command Pattern to undo an action. Please watch the video in the previous post before browsing through this source.

Try to focus on how the commands are all added into the command stack, then you'll see how the stack can be used for undoing, redoing, logging actions, queuing actions, and all sorts of other useful stuff :)

Click on the green, red, and blue boxes to create new circles. Click on the black box to undo.

source

7 comments:

  1. Nice sample, shows perfectly the behavior for the old post. Congratulations John.

    ReplyDelete
  2. мм вот как оказалось !

    ReplyDelete
  3. darien2:56 PM

    it's took me a while to understand the whole flow of the MVC. but i still having hard time understand which one is controller and which one is model

    ReplyDelete
  4. Enrique7:39 AM

    I'm a bit confused about this implementation John, why you don't put the commandHistory array inside the command classes?
    I think a better implementation is to leave the command class to manage the array, this way is not important which invoker is using the command, the action is undoable anyway.
    And to make another command for calling the undo method insidde execute, so our invokers always call execute.
    Even more, an easy way if we are using only one stack, is to create an abstract class for all the commands, with a static commandHistory array.
    But maybe you choose this way for other reasons, can you tell me what are the advantages of this method?
    Thanks!
    Enrique.

    ReplyDelete
  5. Enrique7:48 AM

    Also, I can't see why you are using "Class" for the type of the command in the invoker and creating the class in every clickhandler.

    ReplyDelete
  6. johnlindquist12:42 PM

    Hey Enrique,

    This is a very old post, so I'm not to defend the specifics (I honestly can't remember what the code looks like), but I would keep the history separate from the commands in case the commands are being used across different parts of your app where the same command would need to be put into separate stacks.

    ReplyDelete