- Private constructor to restrict instantiation of the class from other classes.
- Private static variable of the same class that is the only instance of the class.
- Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
Example:
package com.bigbangcode.constructors;public class MySingleTon { private static MySingleTon myObj; /** * Create private constructor */ private MySingleTon(){ } /** * Create a static method to get instance. */ public static MySingleTon getInstance(){ if(myObj == null){ myObj = new MySingleTon(); } return myObj; } public void getSomeThing(){ // do something here System.out.println("I am here...."); } public static void main(String a[]){ MySingleTon st = MySingleTon.getInstance(); st.getSomeThing(); }}
Another example, Thread Safe Singleton:
package com.bigbangcode.singleton; public class ThreadSafeSingleton { private static ThreadSafeSingleton instance; private ThreadSafeSingleton(){} public static synchronized ThreadSafeSingleton getInstance(){ if(instance == null){ instance = new ThreadSafeSingleton(); } return instance; } }
No comments:
Post a Comment