Friday, September 5, 2008

Singleton Pattern

This pattern ensures that there exists only one instance of a class with a global access point to it.
There are any number of cases in programming where you need to make sure that there can be one and only one instance of a class which is shared among the clients.
No client can create an instance of the object from outside. There is only one instance of the class which is shared across the clients. It is named after the singleton set, which is defined to be a set containing one element. For example, your system can have only one window manager or print spooler, or a single point of access to a database engine.
You use the Singleton design pattern when you want to either restrict resource use (instead of creating numbers of large objects without limit) or when you have a sensitive object whose data shouldn’t be accessed by multiple instances (such as a registry).
Creating a single object can also be important when you’re multithreading and you don’t want conflicts in how the data behind that object is accessed. For example, you may be working with a database object, and if multiple threads each create their own database objects — all of which work with the same underlying data store — you could have a serious issue.
UML Diagram :

Let’s say you start with a class named Database that the company programmers have been working with. That class has a simple constructor, as shown in the following code:
public class Database
{
private int record;
private String name;
public Database(String n)
{
name = n;
record = 0;}
}
You need to add two built-in methods, editRecord, which lets you edit a record in the database, and getName, which returns the name of the database.public class Database
{ private int record;
private String name;
public Database(String n)
{
name = n;
record = 0;
}
public void editRecord(String operation)
{
System.out.println(“Performing a “ + operation +“ operation on record “ + record + “ in database “ + name);
}
public String getName()
{
return name;
}
}
Okay so far, but here’s the issue: Whenever you use the new operator toinstantiate an object of the Database class, you have to create a new object. Since you have three uses of databases, you have three objects:Database dataOne = new Database(“Products”);
.
Database dataTwo = new Database(“Products Also”);
.
Database dataThree = new Database(“Products Again”);
.
How are you going to avoid creating a new object each time someone uses the new operator on your class? Here’s one solution — make the constructor private.
private Database(String n)
{
name = n;
record = 0;
}
That stops anyone’s code from using the new operator, except for the codeinside the Database class. But wait a minute — that’s crazy, isn’t it? Who on Earth would have a private constructor? How could you create objects of such a class if you can’t even call the constructor? Sounds good - you give your class a constructor with no public access and let the rest of the world create objects with a utility method that calls that constructor behind the scenes. You can also add code to the utility method to make sure that no more than one object exists. How would that look in the Database class? First, you make the constructor private:
public class Database
{
private int record;
private String name;
private Database(String n) {
name = n;
record = 0;
}
.
.
}
Fine, you can block the use of the new operator from any code not inside the Database class. Now the only way you can create objects of this class is through a utility method, and the usual name for that method when you’re using the Singleton pattern is getInstance (or createInstance, or a more specific name, such as createDatabase). Note that this method should be public and also be static so you can call it using just the database class’s name (as Database.getInstance()).
public class Database
{
private int record;
private String name;
private Database(String n)
{
name = n;
record = 0;
}
public static Database getInstance(String n)
{
}
.
.
}
This method should return a Database object, but that only works when there’s one of those in existence. So the code in this method first checks if that object, which I call singleObject, exists, and if not, it’ll create it. Then it returns that object.
public class Database
{
private static Database singleObject;
private int record;
private String name;
private Database(String n)
{
name = n;
record = 0;
}
public static Database getInstance(String n)
{
if (singleObject == null){
singleObject = new Database(n);
}
return singleObject;
}
.
.
}
In simple words we provide a static method in the class itself, returning an instance of itself. By doing this, we can create one instance upon the first request and keep returning the same instance upon further requests. This is also a form of lazy loading, since it only gets created when it is requested for the first time.

No matter how many times you call getInstance, you’re passed the same
object. Is this going to work as it should? There’s one way to find out.

Testing the Singleton pattern:
Here’s a test harness for the new Singleton Database class, TestSingleton.
java. It starts by getting a Database object named products using the
Database class’s getInstance method and then displays the name of the
Database object, as stored in that object.
public class TestSingleton
{
public static void main(String args[])
{
Database database;
database = Database.getInstance(“products”);
System.out.println(“This is the “ +
database.getName() + “ database.”);
.
.
.
}
}
Then the code gets a Database object from the getInstance method again, this time passing employees as the name to store in the Database object.
public class TestSingleton
{
public static void main(String args[])
{
Database database;
database = Database.getInstance(“products”);
System.out.println(“This is the “ +
database.getName() + “ database.”);
database = Database.getInstance(“employees”);
System.out.println(“This is the “ +
database.getName() + “ database.”);
}
}
But a Database object has already been created, so the second time around, you should still be dealing with the same Database object, not a new one. You can check that by looking at the output of this code:

This is the products database.
This is the products database.


Sure enough, you got the products database both times — the Database class did what it should: Only one Database object was created. There you have it; by restricting access to a class’s constructor and allowing objects to be created only with a utility method, you’ve implemented the Singleton pattern.

Problem solved — now only one object of the Database class exists at one time (although note that there are some multithreading issues coming up, as I discuss in the section “Uh oh — don’t forget about multithreading” later in this chapter). Calling the getInstance method gives you a Database object like the one shown in Figure :
Singleton1
When you call getInstance again, you’re passed the same object as the first time (see Figure below).

No comments: