views:

367

answers:

2

Say I have 4 buttons and I want each one to do a different thing. I don't want a big switch statement where I do a different thing based on which button was pushed, nor do I want a separate method for each button click. Is command pattern a good way to solve this?

A: 

Yes. I've used to help tie in the same Action to a menu click and a toolbar click. It works pretty well. It doesn't revolutionize anything by any means but gives you a lot cleaner code and gets rid of nasty switch statements.

I have code somewhere that I will try to dig up to give you some examples.

Cody C
+3  A: 

Yes, that is a common use for the command pattern. Imagine you have a set of classes (e.g. Open, Save, Print) each of which provides an execute() method, you can then associate an instance of one of these classes with your buttons and the onclick event of the button can call execute() without knowing about the specifics of what the associated command does.

The Wikipedia article gives some other common uses of the command pattern.

mikej
But how to best make the association - inside the button (e.g. have a special "CommandButton" class that keeps a reference to an ICommand ... OR outside the class in some kind of look-up?
Iain