Singleton Design Pattern:
- provides global access to object
- Ensure that only one instance of a class
Implementation:
class s'd contain,
- private constructor.
- private static instance of the class.
- one more public static method which retruns class instance.
Code snippet:
class Sing // Singleton class
{
private static Sing instance; //private static instance
private Sing() {
//Private constructor
}
public static Sing getInstance(){
//
if(instance == null)
instance = new Sing();
return instance;
}
public void display()
{
System.out.println("Singleton onject");
}
}
class Singleton {
public static void main(String[] args) {
Sing.getInstance().display();
}
}
Here, other class cant create instance of this class because of private constructor.
So they can invoke getInstance mehod of the class using class name and it will return class instance.
Usages:
- Logger class : provides global access
- configuration classes
- Accessing shared Resources
Perfecto!! :) like
ReplyDeletePerfect
ReplyDelete