Singleton, I presented in my previous entry is the most common implementation of a Singleton, but still has some defects, among them is that if we do that class serializable in every run would create different levels of singleton and would have to create a method to protect it. And we also have the problem that you can access the private constructor using the Reflection API. So here's a more elegant way to create a Singleton:
Singleton {public enum
INSTANCE;
public void doSomething () {}
}
And then when you would like to use, all you would have to do is this:
public class Main {public static void
main (String [] args) {
Singleton.INSTANCE.doSomething ();
}}
And with that we have a better and simpler implementation of a Singleton ensures that we will always be a single instance.
saludoss!
References:
Blooch, J. Effective Java 2nd Edition
0 comments:
Post a Comment