Wednesday, December 5, 2007

Singleton Pattern

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();
}
}

}

1 comment:

Anonymous said...

Harrah's casino to go public - Aljordan14 retromegabit
Harrah's will air jordan 18 retro red suede super site not run a casino in air jordan 18 retro toro mens sneakers for sale the Ak-Chin area. The casino will have a gaming air jordan 18 retro men online site floor at Harrah's in Ak-Chin show to get air jordan 18 retro red suede Village. 토토사이트 검증 샤오미