Searching...
Thursday, 20 September 2012

Java Singleton Pattern Example

00:22

Where to use & benefits:

  1. Ensure unique instance by defining class final to prevent cloning.

  2. May be extensible by the subclass by defining subclass final.

  3. Make a method or a variable public or/and static.

  4. Access to the instance by the way you provided.

  5. Well control the instantiation of a class.

  6. Define one value shared by all instances by making it static.

1. Create a java class with Private Constructor and static getInstance

package pretechtest;
public class SingleTon {
	private static SingleTon singleTonInstance;
	//private constructor
	private SingleTon() {
	}
	//public static get instance
	public static SingleTon getSingleInstance() {
		if (singleTonInstance == null) {
			synchronized (SingleTon.class) {
				if (singleTonInstance == null) {
					singleTonInstance = new SingleTon();
				}
			}
		}
		return singleTonInstance;
	}
}

2. Create a java class to test singleton

package pretechtest;
public class SingleTonTest {
	public static void main(String[] args) {
		System.out.println(SingleTon.getSingleInstance());
		System.out.println(SingleTon.getSingleInstance());
		System.out.println(SingleTon.getSingleInstance());
		System.out.println(SingleTon.getSingleInstance());
	}
}

3. Output



pretechtest.SingleTon@f6a746
pretechtest.SingleTon@f6a746
pretechtest.SingleTon@f6a746
pretechtest.SingleTon@f6a746


0 comments: