Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top