[java-gnome-hackers] Singleton implementation in java (was Re: sourceview development branch)
Brought to you by:
afcowie
From: Vreixo F. <met...@ya...> - 2009-05-23 11:35:55
|
Hi! > > > The only thing that really caught my eye so far was > > > LanguageManager.getDefault(); > > [...] > > > Another option would be to turn LanguageManager into a real > singleton [...]. The > > LanguageManager would then be accessed like this: > > LanguageManager.getInstance(); that does not remove the static > method but would make it more explicit that you are using one. Maybe > that would fit better? > > Nah, not really. > I also hate singleton pattern in the way it is teached (and commonly used) in Java language. I'm now using an alternative that is much better, imho: expose instance methods as static. I mean, if you have a LanguageManager singleton, with a method getLanguage(), as in your example instead of calling: LanguageManager.getDefault().getLanguage("java") you write: LanguageManager.getLanguage("java") Internally, LanguageManager keeps a reference of the single instance, and delegates all methods in that instance. It could be something like this: public final class LanguageManager { // single instance private static final LanguageManager instance = new LanguageManager(); // private constructor private LanguageManager() { } // private instance methods private XXX getLanguage(String l) { .... } // and public static methods... public static XXXX getLanguage(String l) { //... that delegate on the instance return instance.getLanguage(l) } } In my opinion this creates clear code, but I know everybody is using the getInstance() traditional approach... Cheers Vreixo |