Software DevelopmentHow To Use Singleton Design Pattern In Java

How To Use Singleton Design Pattern In Java

Many of us are well aware of the fact that different design patterns primarily signify the best practices that are used by experienced object-oriented software developers. In fact, it won’t be wrong to consider that these design patterns act as solution to general problems that very often many software developers usually face in the phase of software development. The most important aspect that one require to note is that these solutions are attained by trial and error by numerous software developers over quite a substantial period of time.

Treatment of Design Pattern

In 1994, four authors Ralph Johnson, Richard Helm, Erich Gamma, and John Vlissides published a book titled Design Patterns – Elements of Reusable Object-Oriented Software which commenced the idea of Design Pattern in Software development.

Design patterns offer a standard terminology. Over the period of time, various design patterns have been evolved and they had offered best solutions to different issues. Getting familiar with these patterns can be very beneficial for any software developer to learn software design in an easy and effective way.

Java Singleton Pattern is one of the Gangs of Four Design patterns and is available in the Creational Design Pattern category. If we go as per the definition then it may seem to be a very simple design pattern but its implementation requires a good knowledge as it comes with various implementation concerns. In fact, successful application of Java Singleton pattern has always been a contentious subject among most of the JAVA developers.
Let us try to have a comprehensive idea about Singleton design pattern principles, along with few best practices for its usage.

Singleton Design Pattern In Java

To apply Singleton pattern, one can opt different approaches but most of them have following common concepts.

  • Private constructor to restrict instantiation of the class from different classes.
  • Private static variable of the similar class that is the only instance of the class.
  • Public static system that returns the instance of the class, which is the global access point for external world and acquire the instance of the singleton class.

Singleton pattern is one of its kinds of a design solution where an application require having one and only one instance of any class, in every possible circumstance. This type of design pattern comes under creational pattern and provides an ideal way to make an object. An important aspect to remember is that it contains a single class that helps in creating an object and help in getting access to its only object of the class.

You must not forget the fact that in Java the Singleton pattern helps in ensuring that there is just one instance of a class which is developed. Adding to that, it is primarily with an aim to facilitate easy and effective global point of right to use to the object. Moreover, if you talk context of practical usage then Singleton patterns are generally used in thread pools, logging, caches, device driver objects, and configuration settings.

Singletons are useful to provide a unique source of data or functionality to other Java Objects. For example, you may use a singleton to access your data model from within your application or to define logger which the rest of the application can use.

Implementation

To implement this design pattern we require counting the following steps:

Step 1: First of all make sure to introduce a default Private constructor:

Java implementation

Step2: In the second step you would require to design a method to get the reference to the Singleton Object.

Singleton Object

NOTE: It is important to understand that in the above programming text we mentioned a public static getter or access method with a key objective to acquire the instance of the Singleton Object during runtime. As the object has been created first inside this method is null.

A successive call to this method performs the return operation returning the same created object. Adding to that in this case the object has been declared (private).

Step.3: Now synchronize the Access method to prevent Thread Problems

public static synchronized SingletonObjectDemo getSingletonObject()

Now, it might happen that the access method can be called twice right from 2 diverse classes at the same time and consequently more than one object could be created, which unfortunately disturbs the design patter principle. To overcome from any such scenario, we can easily add the synchronized keyword right at the declaration.

Step.4: Finally, it is always good to override the Object clone method as it helps in preventing the cloning.
Design a copy of the Object by cloning it and making a right use of the Object’s clone tactic as shown below:

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

NOTE: This violates the Singleton Design Pattern’s objective, but not to worry as you can easily overcome from this just by overriding the Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

Finally, have a look at the program shown below as the final Implementation of Singleton Design Pattern in java, by making the use of all the steps stated above.

final Implementation

Let us have also look at few more examples using Volatile Keyword.

We can also make use of the volatile keyword to the instance variable declaration.

private volatile static SingletonExample singletonInstance;

volatile keyword

The volatile keyword can be very effective and act as concurrency control tool in a multi threaded environment. It helps in providing the latest update in a most accurate manner.

Singletons are primarily defined by using an object orientated approach. In Singleton pattern only one object is designed for the class and that particular object is then made public or shared right across all the clients, and this approach turns very effective in a situation when we require making something centralized. This approach gets effective in creating a logged file for entire application, as it helps tracking whatever error generated for the clients from a single file. Thus, we just can’t ignore the significance of a singleton pattern. Singleton pattern looks a simple implementation, but it must be used only if there is a strong requirement for it. 

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -