Singleton Pattern is a design pattern that allows a user to create only one object for a class.
There are three things to be followed to create a singleton pattern or a singleton class.
1. The class should implement a private constructor. (This is done so that the user is not allowed to create an object with the help of new operator).
2. The class should have a private static instance of the same class. (If the class name is Book, then there should be a private static object of Book within the Book class).
3. There should be public static factory method called getInstance() to retrieve the private object to the user.
Code Sample:
public Book{
private static Book oneBook = null;
private Book(){
}
public static Book getInstance(){
if (oneBook == null){
oneBook = new Book();
}
return oneBook;
}
}
The above code may be prone to create multiple objects in case of threading. So, in case of threading, use synchroniation.
public static Book getInstance(){
//Thread safe factory method
if(oneBook == null){
synchronized(Book.class){
oneBook = new Book();
}
}
}
Wednesday, December 5, 2007
Subscribe to:
Posts (Atom)