R – How to use the command pattern to reduce the complexity of a menu


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?

Best 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.