Java EE 8 Design Patterns and Best Practices
上QQ阅读APP看书,第一时间看更新

Explaining Singleton

In a software project, in some solutions, we may want to ensure that a class has only one instance of an object throughout the project and that this object is accessible at any point in the project. Creating a global instance or static instance will not ensure that this class will not be used at another point in another instance. The best way to solve this is by using the Singleton pattern, which ensures that there is only one instance of a class in the entire project. In the following diagram, we are showing the structure of Singleton and how it is designed:

Here, we have one class called Singleton which has a private constructor, as well as a reference variable of Singleton and a method for returning its unique instance. A good example of an application is a situation in which we want to create a class responsible for application configurations (paths to some resource, parameters to access filesystems, behaviors of the environment). Often, the application has some configurations and we need a class to represent these application configurations. Thus, this class of application configuration doesn't need various instances, but only one instance. 

Another application of Singleton is when we want to create an Abstract Factory that will be explained in the following subsection. Generally, we will have only one Abstract Factory throughout the application. With this, we can use a Singleton to guarantee that we will have only one instance of Abstract Factory.

This pattern is often used in frameworks and APIs, but it is common for this pattern to be found in the code of projects, mainly on Java EE.

The use of the Singleton pattern can be a good practice depending on the scenario, but depending on the scenario the use of Singleton can be a bad practice. The Singleton should not be used when the object is stateful and maintain a state, because with Singleton the same instance of the object is shared by all processes of application and if some process updates a state of this object all processes of application will be impacted by this update. Furthermore, we can have a problem with the concurrent update of the state of a Singleton.