Posts Tagged ‘design pattern’

Design Pattern - Singleton

Wednesday, September 17th, 2008

The Singleton Pattern is quite simply a design pattern that allows only one instance of itself to be created per application pool or application instance and provides one point of access to the single unique instance.

Ensure a class only has one instance, and provide a global point of access to it.

public class Singleton {

	protected Singleton() { }

	private static Singleton _instance = null;
	/**
	 * @return The unique instance to this class.
	 */
	public static Singleton getInstance() {
		if(null == _instance) {
			_instance = new Singleton();
		}
		return _instance;
	}
}



As you can see the idea is not to use public constructor. With protected or private constructor in some other class we can not do something like this:

Singleton objSingleton = new Singleton();

The other idea is to use static method getInstance();

this is how it works in some test client:

public class TestSingleton() {
    public static void main(string[] args) {
        Singleton objSingleton;
        objSingleton.getInstance();
    }
}
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in