Select Page

Singleton

Singleton

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

Statically Initialized
The singleton class is implemented by defining a static field that is statically initialized (that is, the field is initialized when the class is initialized). This has the advantage that invocations of the method used to access the singleton do not incur the overhead of checking whether or not the instance has been created.

Dynamically Initialized
The singleton class is implemented by defining a static field that is dynamically initialized (that is, the field is initialized the first time its value is requested). This has the advantage that the singleton is not allocated unless it is needed, potentially reducing memory usage.

Links

Source Code

/**  * Represents a singleton.  */ public class Singleton { 	/** 	 * Holds the singleton instance. 	 */ 	private static Singleton instance;  	/** 	 * constructor must be private to avoid automatic creation of default 	 * constructor by the compiler 	 *   	 */ 	private Singleton() { 		super(); 	}  	/** 	 * Returns the singleton instance. 	 *  	 * synchronized to prevent race problem 	 *  	 * @return the singleton instance 	 */ 	public static synchronized Singleton getInstance() { 		if (instance == null) { 			instance = new Singleton(); 		} 		return instance; 	} } 

Singleto

About The Author

I worked with various Insurances companies across Switzerland on online applications handling billion premium volumes. I love to continuously spark my creativity in many different and challenging open-source projects fueled by my great passion for innovation and blockchain technology.In my technical role as a senior software engineer and Blockchain consultant, I help to define and implement innovative solutions in the scope of both blockchain and traditional products, solutions, and services. I can support the full spectrum of software development activities, starting from analyzing ideas and business cases and up to the production deployment of the solutions.I'm the Founder and CEO of Disruptr GmbH.

Categories