So, I'm developing a program using the Swing library and I obviously have buttons and menu items. Some of these are supposed to do the same stuff, and I thought using the Command Pattern should be the way to do it, e.g. I have a "save" button and a "save" menu item and they have to implement the same saving algorithm. Command Pattern seems to be ok but I can't get who's the receiver in all that. Isn't a comand supposed to work on an object which implements some sort of "receiver interface", so that you can use different commands on different receivers coupling them aribtrarily? It looks like there's no "receiver" in my implementation of the pattern. Another doubt i have is should a command be implemented as a singleton, since you could potentially call its functions from differents parts of the same project, and it would be handly to instantiate it only once and make it statically invokable?
Thank you.
As @nIcEcOw noted, that's what
Action
s are for. This Answer Shows exactly this.As stated in the How to use Actions :
An There only three
Actions
. Ont to open, save, and new. EachAction
has anActionCommand
, andicon
, and and action to perform. Both theJMenuItem
andJToolBar
button share the sameAction
and do the same thing. Here is the code you can run.As stated in the quote from the above mentioned tutorial, you can do more than just add an image and an action command to the
Action
. You can use it to set mnemonics and accelorators. Here is a customAction
class that takesand a key accelorator.
Here's an instantiation of this
Action
And here's the new result. You will see the
actionCommand
in the menu, along with the key mnemonics and accelerators, tooltips, and you will see the jtoolbar buttons share the same traits. You will also see in the final code, that never once once a component created. All you do is add theAction
to theJToolBar
and theJMenu
and let them work their magic.UPDATE
The better explain the relationship of
Action
and Command PatternsAs noted in Command Pattern
So basically Swing uses the concept of the command pattern through the use of
Actions
As for OP's question
As for the receiver, the wiki uses a text editor as an example and defines the receiver as such
The main more components of a Command Pattern are stated as follows
Four terms always associated with the command pattern are command, receiver, invoker and client.
So to put it all together:
actionPerformed
which in turnThe wiki article is good read with a Java example
When two or more components are mean to do exactly the same thingy, one should look at Action, which reduces the duplicate code.
Small example for further help :
ADDED an example with SINGLETON PATTERN (though I am not sure of this approach(about how good this approach is))