- Allows to create a unique object by giving a global point of access, ensuring object is created only when is required.
- Constructor is declared private, hence class cannot be subclassed/ extended.
// A Thread Safe Singelton Example, Lazy creation
public class Singleton {
private static Singleton myInstance = null;
private Singleton() { }
public static synchronized Singleton getInstance() {
if ( myInstance == null ) {
myInstance = new Singleton();
}
return myInstance();
}
}
// Egarly created thread safe example. Thread safe delegated to JVM
public class Singleton {
private static Singleton myInstance = new Singleton();
public static getInstance() {
return myInstance();
}
}
Difference between Singleton and Static Class
- Singleton can extend classes and implement interfaces, while a static class cannot (well, it can extend classes, but it does not inherit their instance members).
- Singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded. A sinlgeton class can be extended and it's methods overidden.
- Singletons can be handled polymorphically without forcing their users to assume that there is only one instance. For instance, assume you have a Configuration class that holds some global configs. Methods that use this configuration information may be defined as:
public void doSomething(Configuration config) {...}
When you start writing your system you may have only one global instance, so you make Configuration a singleton. But at some later point you may want to support more than one configuration set. Maybe you'd want to allow the user to load a Configuration object from and external file or or programmaticaly create his own (this happened in my code several times). Provided that the classes or methods that use a configuration object allow the user to pass his own instance, most of your code need not be aware of the "global" nature of the class and is therefore more flexible.
- Singletons can be handled polymorphically without forcing their users to assume that there is only one instance. For instance, assume you have a Configuration class that holds some global configs. Methods that use this configuration information may be defined as:
public void doSomething(Configuration config) {...}
When you start writing your system you may have only one global instance, so you make Configuration a singleton. But at some later point you may want to support more than one configuration set. Maybe you'd want to allow the user to load a Configuration object from and external file or or programmaticaly create his own (this happened in my code several times). Provided that the classes or methods that use a configuration object allow the user to pass his own instance, most of your code need not be aware of the "global" nature of the class and is therefore more flexible.
References:
No comments:
Post a Comment