I'm not sure where I've read this from, but somehow, this statement got stucked in my mind:- "Use the Command Pattern whenever you come upon code with a huge switch statements. Switch statements are not OO." Comments ? Pho
Let's say you have a program that expects one of several known arguments as input. For example, it's a game, and the player can run, sleep, eat, hide, etc. One solution might be to 'switch' based on the command type, where each case in the switch does some necessary variable setting and calls the appropriate function run(), sleep(), eat(), hide(), etc. As these structures add more cases, however, they become more difficult to read and maintain. A Command Pattern could be used to treat each case as a subclass of a generic Command, for example. Each object contains specific behavior, and becomes easier to add, remove, and debug because it is self-contained. A switch statement would probably be computationally faster, ultimately, but is the effort required to debug and maintain a big one worth it? Using the Command pattern as a guide, you avoid potentially monolithic code structures, possibly sacrificing speed of computation to achieve more readable code. ------------------ Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide [This message has been edited by Michael Ernest (edited February 11, 2001).]
Make visible what, without you, might perhaps never have been seen. - Robert Bresson
I got inspired, and pulled out GoF to explain this pattern is more detail. Here's a really quick and dirty example:
Actually, that example could use a few more passes before it's worth talking about, but I've played out the roles, anyway. We'd probably all like to see the Player object as an Invoker of the Command rather than GameController. I was just rattling along here without much forethought, but I hope the premise is apparent. ------------------ Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide [This message has been edited by Michael Ernest (edited February 11, 2001).]
As I recall, another nice thing about the Command pattern is that you can provide an easy UNDO function if you keep a list of the last ## Command objects. Naturally your Command object must provide for storing the previous state. Bill
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: Command Pattern - what is it applicable for ?