Wednesday, September 22, 2010

Singleton Pattern

The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

Singleton Code Example

public final class MySingleton {

private static MySingleton instance;

private MySingleton(){ }

public static MySingleton getInstance(){

if(instance==null){

instance = new MySingleton();

}

return instance;

}

}


note:

Thread safety warning!

As shown above, the singleton is not thread safe. Used properly, singletons can be beneficial. Some people believe they are just evil. There are two camps, as usual. An alternative to the Singleton pattern is using a factory class to manage singletons. In other words, inside of a factory class, you can ensure that one and only one object is created.

If you are thinking about implementing this pattern, please review the following article first:

- Two approaches to creating thread-safe singletons

- "Effective Object-Oriented Design," and " Class Instances,

No comments:

Post a Comment