Command Pattern Question

P

Peter Mueller

Hello,

I have a basic question about the command pattern.

Let's assume there is a command AddItemCommand and another one
RemoveItemCommand.

The implementation of execute() in the AddItemCommand is basically the
impl. of undo() in the RemoveItem command and vice versa. If this is
the case. How can code duplication be avoided using the command
pattern?

Probably I missed something general with with command pattern.

Thanks for your help.

Peter
 
S

Stefan Ram

Peter Mueller said:
The implementation of execute() in the AddItemCommand is basically the
impl. of undo() in the RemoveItem command and vice versa. If this is
the case. How can code duplication be avoided using the command
pattern?

In pseudo-code and simplified:

class AddItemCommand
{ void do(){ CommandImplementations.addItem(); }
void undo(){ CommandImplementations.removeItem(); }}

class RemoveItemCommand
{ void do(){ CommandImplementations.removeItem(); }
void undo(){ CommandImplementations.addItem(); }}
 
M

markspace

Peter said:
The implementation of execute() in the AddItemCommand is basically the
impl. of undo() in the RemoveItem command and vice versa. If this is
the case. How can code duplication be avoided using the command
pattern?


I'm going to go with Peter Doniho on this and say use a different class.
Not everything should be push into the Commands themselves. Your MVC
controllers still have to do some work.

Iirc, there are two queues in the Command pattern, the undo queue and
the redo queue. When a command gets executed, it goes in the undo
queue. When you execute an undo, you pull the first command out of the
undo queue, execute its undo method, and put it on the Redo queue. When
you execute a redo command, you pull the first item out of the Redo
queue, execute it, and the put it in the Undo queue.

Both of these operations could be made external to the command class
itself, and maybe should be. A little separation of concern can't hurt,
and this seems like a good place to provide some, rather than trying to
cram absolutely everything into one single Command class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top