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

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).

主站蜘蛛池模板: 金沙县| 新干县| 广州市| 龙泉市| 博乐市| 安达市| 翼城县| 英吉沙县| 扶余县| 乳源| 桐梓县| 宁乡县| 房山区| 高青县| 内丘县| 禄丰县| 东宁县| 蓬溪县| 凤山县| 泊头市| 江北区| 吉隆县| 武强县| 文登市| 西盟| 富源县| 运城市| 沙洋县| 合阳县| 游戏| 江津市| 闸北区| 邳州市| 霍城县| 时尚| 大兴区| 孝义市| 泰和县| 抚顺县| 马龙县| 乐陵市|