0

All the examples and tutorials I found online so far deal with commands that either add or subtract or some other operation on a value - Calculator is the common example.

However What if you have commands that don't behave like those in a calculator?

Imagine a drawing program like Microsoft Visio, where user places and moves objects on the screen to an x, and y position. Or adding and removing an object. These commands are unrelated, so keeping track of a current x, y position, has no meaning if the next command in the stack is a create object command that you need to undo.

Any suggestions how to handle this?

sjs
  • 472
  • 1
  • 5
  • 15
  • The command pattern is not _really_ to provide an "undo". At its core, it provides a way to decouple implementation from the operation you are doing, e.g., if you have a button that will move the object to the middle of the screen, using the Command pattern, the button will merely call something like `moveToMiddle(obj)` - it doesn't need to know that the "real" implementation is `obj.setX(width/2); obj.setY(height/2)`, as that implementation can change. If you want to undo, look at what Redux does - each command will be a modification, and you can roll them back by applying the reverse. – VLAZ Dec 13 '16 at 16:43
  • 1
    That relies on keeping a consistent state, however. For a more "relaxed" solution, you can combine Command and Memento in order to keep a snapshot of what was happening before. That way rolling back a Command is restoring the snapshot. – VLAZ Dec 13 '16 at 16:46

1 Answers1

0

Assume "moving object on axis" + proper command is a "object". Then command patterns deal that object and contained command. So command pattern does not implicate "preserving state of that object". Each time, it is no matter that input object is same or different.

In the case of calculator, "delete command" will be as same as "remove object command".

Before this discussion, what is your purpose to use command pattern for moving object?

Teddy
  • 1
  • 1
  • I do not currently use command pattern. I was thinking of it as a solution for adding undo/redo feature to my application. I found this similar question here http://stackoverflow.com/questions/3250104/fast-undo-redo-with-memento-command-pattern – sjs Dec 14 '16 at 17:52