Let us create an object and re-use it throughout the application wherever needed. Therefore, not more than a single instance of the class exists. This is called as a Singleton pattern.
In general, we create a self composed class with a closed constructor. So that, the instantiation can be customized with the help of a factory method.
Following class diagram shows a singleton class,
In the book class we made the constructor private and defined a static method getInstance().The object creation activity is delegated to the custom getInstance() method and the constructor is closed. As a result, we validate the object whether it already exists or not.
The getInstance() method will not create an instance if one already exists.
class Book{
private static Book book;
private Book() {
}
public static Book getInstance(){
if(null==book)
book=new Book(); // Lazy Initialization
return book;
}
}
The above sample is based on Lazy Initialization pattern.
One simpler way to create the same singleton class without Lazy Initialization is given below,
class Book{
private static final Book book=new Book();
private Book() {
}
public static Book getInstance(){
return book;
}
}
We have one more approach to achieve a perfect singleton with the help of enum types.
Since the data members of the enum types are always constants,the method calls will be happening over a singleton object.
Following design will explain the concept clearly.
Here, Book is a enum type having a constant INSTANCE which can act as a singleton.
Using the singleton object INSTANCE, we can invoke the method getPrice() from the enum Book.