java - Singleton Action versus Multi instance Action -
i have dude how implement actions in swing.
my idea create class each action of application extending abstractaction can use in many components must have same behavior. finaly have as:
public class actionexample extends abstractaction { @override public void actionperformed(actionevent arg0) { system.out.println("do something"); } }
well, when want use have 3 options in mind:
public void makeui1() { jbutton btn = new jbutton(new actionexample("do it")); jmenuitem mi = new jmenuitem(new actionexample("do it")); } public void makeui2() { action = new actionexample("do it"); jbutton btn = new jbutton(a); jmenuitem mi = new jmenuitem(a); }
or use singleton (also changing actionexample):
public void makeui2() { jbutton btn = new jbutton(actionexample.getinstance()); jmenuitem mi = new jmenuitem(actionexample.getinstance()); } public class actionexample extends abstractaction { private static final actionexample instance = new actionexample("do it"); public static action getinstance() { return instance; } @override public void actionperformed(actionevent arg0) { system.out.println("do something"); } }
my first opinion make through singleton instance see in oracle tutorial make new instance before setting components , in see many code create new instance each component don't know it's better , why.
is preferred 1 method used on other?
the multi instance action allows save data in moment of action further use.
imagine want add undo/redo functionality. need save actions have been done every action.
singleton not provide advantage in case.
Comments
Post a Comment