Thursday 30 June 2011

Modified Command Pattern

Recently I came across a problem of how to implement common interface for executing commands on objects of different types. Only one command can be assigned to each object. Each command has different implementation for each type of object but commands are accessed on each object through same interface. I wanted to have something like this:

I came up with the solution which uses abstract class (CCommand) in order to achieve common interface (Execute()) and command classes templated on actual object type in order to specialize Execute() implementation for each type.

Command.h:



CommandAdd.h:


CommandRemove.h:


UpdateGroupsCollection.h:


CUpdateFilesCollection.h:


main.cpp:


Output:

Group1 added to Update Groups
File1 added to Update Files
Group1 removed from Update Groups
File1 removed from Update Files

To avoid having SetCommand()/GetCommand() code repeated in all client classes, we can use intermediate class, let's call it CCommandManager. This simplifies client classes - they just need to contain one instance of CCommandManager and perform all command-related actions through it:

CommandManager.h:


UpdateGroupsCollection.h:


CUpdateFilesCollection.h:


main.cpp:


Templated commands can be avoided if commands become inner classes of all classes they need to be performed on. E.g.

UpdateGroupsCollection.h:


main.cpp:

No comments: