官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 嘉峪关市| 合江县| 榆社县| 建水县| 鲁山县| 通渭县| 铜山县| 文水县| 西林县| 文水县| 庆安县| 上犹县| 平塘县| 合阳县| 阳泉市| 五大连池市| 嘉黎县| 承德市| 岐山县| 平昌县| 镶黄旗| 建始县| 任丘市| 广河县| 调兵山市| 富宁县| 广宗县| 邵东县| 安庆市| 靖边县| 云和县| 称多县| 莫力| 洪洞县| 泰兴市| 宜君县| 临潭县| 富源县| 韶关市| 绥江县| 台山市|