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

Understanding the Singleton design pattern

Singleton provides you with a mechanism to have one, and only one, object of a given type and provides a global point of access. Hence, Singletons are typically used in cases such as logging or database operations, printer spoolers, and many others, where there is a need to have only one instance that is available across the application to avoid conflicting requests on the same resource. For example, we may want to use one database object to perform operations on the DB to maintain data consistency or one object of the logging class across multiple services to dump log messages in a particular log file sequentially.

In brief, the intentions of the Singleton design pattern are as follows:

  • Ensuring that one and only one object of the class gets created
  • Providing an access point for an object that is global to the program
  • Controlling concurrent access to resources that are shared

The following is the UML diagram for Singleton:

A simple way of implementing Singleton is by making the constructor private and creating a static method that does the object initialization. This way, one object gets created on the first call and the class returns the same object thereafter.

In Python, we will implement it in a different way as there's no option to create private constructors. Let's take a look at how Singletons are implemented in the Python language.

Implementing a classical Singleton in Python

Here is a sample code of the Singleton pattern in Python v3.5. In this example, we will do two major things:

  1. We will allow the creation of only one instance of the Singleton class.
  2. If an instance exists, we will serve the same object again.

The following code shows this:

class Singleton(object):
     def __new__(cls):
       if not hasattr(cls, 'instance'):
         cls.instance = super(Singleton, cls).__new__(cls)
       return cls.instance

s = Singleton()
print("Object created", s)

s1 = Singleton()
print("Object created", s1)

The output of the preceding snippet is given here:

In the preceding code snippet, we override the __new__ method (Python's special method to instantiate objects) to control the object creation. The s object gets created with the __new__ method, but before this, it checks whether the object already exists. The hasattr method (Python's special method to know if an object has a certain property) is used to see if the cls object has the instance property, which checks whether the class already has an object. Till the time the s1 object is requested, hasattr() detects that an object already exists and hence s1 allocates the existing object instance (located at 0x102078ba8).

主站蜘蛛池模板: 沂水县| 无锡市| 金山区| 肇州县| 自治县| 丹凤县| 营口市| 昌吉市| 和龙市| 广宗县| 滨州市| 莱芜市| 象州县| 达州市| 蚌埠市| 明溪县| 云霄县| 穆棱市| 同德县| 铁力市| 时尚| 白河县| 麦盖提县| 珲春市| 富锦市| 启东市| 昌宁县| 鄢陵县| 五台县| 甘孜县| 武隆县| 横山县| 仙居县| 黎平县| 汉阴县| 寿宁县| 正定县| 军事| 桂林市| 太原市| 泰宁县|