Design Patterns Revisited - Singletons, How Single They Are..
Join the DZone community and get the full member experience.
Join For FreeI decided to write several posts about design patterns. Whether you use them or not, they are important and make your life easier (and probably increase your salary). Even if you are really not interested in design patterns, you will face questions about them in interviews or architectural design meetings. So you better open up your brain and learn some - there's nothing wrong with impressing a few colleagues.
The first pattern I will post is the Singleton Pattern. The mighty gof explains this pattern as follows; "Ensure a class only has one instance, and provide a global point of access to it.".
Simple isn't it, if you need only one instance of a resource, mostly because it would be expensive to create and hold new instances, you make sure there is only one unique living instance of that object. Singleton objects are God and if you don't want chaos, conspiracy and fighting like Olympian Gods than you must make sure you have only one!
public class SingletonObj {
private final static Singleton instance = new Singleton(); // our unique instance
private Singleton() {} //A
public static Singleton getInstance() { //B
return instance;
}
}
public class SingletonObj {
private final static Singleton instance = null;
static {
instance = new Singleton(); // our unique instance
}
private Singleton() {} //A
public class SingletonObj {
private final static Singleton instance = null;
private Singleton() {} //A
public static Singleton getInstance() { //B
if (instance == null){
instance = new Singleton(); // our unique instance
}
return instance;
}
}
public class SingletonHack {
public static void main(String [] args);
Class clazz = Class.forName("SingletonObj"); //we load the class
Constructor[] cons = clazz.getDeclaredConstructors(); //get the constructors
cons[0].setAccessible(true); //change access rights
SingletonObj noMoreSingleton = (SingletonObj) cons[0].newInstance();
//we have brand new instance
}
Opinions expressed by DZone contributors are their own.
Comments