Pergunta

Digamos que eu tenha 4 botões e quero que cada um faça uma coisa diferente. Não quero uma grande instrução Switch, onde faço uma coisa diferente com base em qual botão foi pressionado, nem quero um método separado para cada botão clicar. O padrão de comando é uma boa maneira de resolver isso?

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top