Wednesday, May 16, 2007

Singleton

Few days ago, my friend asked me about what is the point of Singleton? Well.. For this last four month, I never touch this kind of thing, Singleton and other kind of design pattern. So, I wasn't confident enough when I tried to explain what's the point of Singleton. But, because I used to use this design pattern and I think, it is the most frequent design pattern I've ever used, I still remember what Singleton is and what it is for.

In my opinion, Singleton is a design pattern which ensure a class only has one instance. I usually use it to provide a global access to a class, like a global variable which is accessible through all part of my codes. And it should be more efficient because it only has one instance.

Singleton pattern is implemented by creating a class which is responsible for keeping track of its sole instance and ensure that no other instance can be created. Finally, the class should provide a way to access the instance. This can be done by creating a static method which will check whether the instance of the class is already exist. This method will create a new instance if one doesn't exist and returns a reference to the instance if it already exists. The instance of the class is only accessible using this static method. To prevent the other way of instantiating object, the constructor of the class is made private or protected.

Below is an example of Singleton implementation using Java:


public class Singleton{

private static Singleton instance;

// Private constructor to prevent other class
// instantiate this Singleton class directly
private Singleton(){
}

// A static method which is used to access the instance
public static synchronized Singleton getInstance(){
if ( instance == null ){
instance = new Singleton();
}

return instance;
}

.
.
.

...
}



Notes that the synchronized keyword in the getInstance method is used to ensure that no more than one thread could access this method at the same time. If this method is being accessed by a thread, then another thread which will access this method will wait until first thread is finished. This is the way to enforce thread-safe programming.

To implement and use this Singleton pattern, just simply write:


Singleton singleton;
Singleton = Singleton.getInstance();

2 comments:

Anonymous said...

yang nanya awalannya S yah? :D

~ipun
~cieee ekkoooooo :D heheheh

Eko Budi Prasetyo said...

tau aja lo, lo jg ditanya-tanyain yah ama dia?