Singleton Design Pattern is a convention for ensuring one and only object is instantiated for a given class.
What use is that?
There are many objects that we need only one of: thread pools, caches , objects that handle preferences and registry settings.
The singleton pattern also gives us a global point of access , just like a global variable.With Singleton pattern you can:
- Ensure that only one instance of a class is created
- Provide a global point of access to the object
- Allow multiple instances in the future without affecting a singleton class's clients.
public class Singleton {
private static Singleton uniqueInstance ;
// other useful instance here
private Singleton () { }
public static Singleton getInstance() {
if ( uniqueInstance == null ) {
uniqueInstance = new Singleton ();
}
return uniqueInstance ;
}
Dealing with Multihtreading ?
public class Singleton {
private static Singleton uniqueInstance ;
// other useful instance here
private Singleton () { }
public static synchronized Singleton getInstance() {
if ( uniqueInstance == null ) {
uniqueInstance = new Singleton ();
}
return uniqueInstance ;
}
No comments:
Post a Comment