Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the command pattern

I am in the design process of an application, and I would like to use the command pattern for undo/redo purposes. I did some research into the command pattern but the only thing I don't get is: Should a command have the undo and redo methods, or should I make two separate commands, one for undo and one for redo, and call those from the main command itself?

like image 722
slayerIQ Avatar asked Feb 06 '10 21:02

slayerIQ


People also ask

What is implementation in design pattern?

Implementation of a design pattern can take many forms according to the programming language being used. Most of the literature presents design patterns in their conventional object-oriented implementations. Several other studies show the implementation in aspect-oriented languages such as AspectJ, EOS, and Caesar.

How does the Command pattern work?

In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

When would you use the command design pattern?

Command design pattern should be used when the caller of an operation doesn't necessarily need to know how to perform the operation. Example: A button UI component doesn't need to know how to perform the operation when it is clicked. 2.

Where is Command pattern used in Java?

java . The Command pattern turns the request itself into an object. This object can be stored and passed around like other objects. The key to this pattern is a Command interface, which declares an interface for executing operations.


2 Answers

The command object itself should implement the undo / redo functionality.

The commands are generally pushed and popped from a stack maintained by a command manager to implement multi level undo. When commands are executed they are pushed onto the stack and when they are undone they are popped from the stack.

The memento pattern would be used in conjunction with the command pattern, it is not a replacement to the usage of the command pattern. It would be used to maintain the state required for the undo operation.

like image 135
David Avatar answered Oct 01 '22 13:10

David


You might also want to consider the memento pattern for this, we use it and it works brilliant for undo.

like image 39
Burt Avatar answered Oct 01 '22 11:10

Burt