Introduction
In this quick article, we'll discuss the two most popular ways of implementing Singletons in plain Java.
Class-Based Singleton
The most popular approach is to implement a Singleton by creating a regular class and making sure it has: 1. A private constructor 2. A static field containing its only instance 3. A static factory method for obtaining the instance We'll also add an info property, for later usage only. So, our implementation will look like this: While this is a com...
Enum Singleton
Moving forward, let's discuss another interesting approach – which is to use enumerations: This approach has serialization and thread-safety guaranteed by the enum implementation itself, which ensures internally that only the single instance is available, correcting the problems pointed out in the class-based implementation.
Usage
To use our ClassSingleton, we simply need to get the instance statically: As for the EnumSingleton, we can use it like any other Java Enum:
Common Pitfalls
Singleton is a deceptively simple design pattern, and there are few common mistakes that a programmer might commit when creating a singleton. We distinguish two types of issues with singletons: 1. existential (do we need a singleton?) 2. implementational (do we implement it properly?)
What are the benefits of using a singleton class?
Singleton class restricts the object creation for a class to only one in the java virtual machine. It also helps in providing a global access point to the object. This design pattern is commonly used in caching, Abstract Factory, logging, Prototype, etc. It is also used in core java classes such as java.awt.Desktop, java.lang.Runtime.
What is the difference between a Singleton Class and a normal Class?
The other difference is that a normal class vanishes at the end of the lifecycle of the application while the singleton class does not destroy with the completion of an application. Early Instantiation: The object creation takes place at the load time.
How do you implement a singleton class?
A singleton class in Java is the one which can have only one object. The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance (). The private field can be assigned from within a static initializer block or, more simply, using an initializer.
What are some examples of singleton classes?
The example of singleton classes is Runtime class, Action Servlet, Service Locator. Private constructors and factory methods are also an example of the singleton class. By using the class name if we are calling a method and that method returns the same class object such type of method is called a factory method.