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

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

主站蜘蛛池模板: 卢湾区| 峨边| 沂南县| 东阿县| 安阳市| 武夷山市| 师宗县| 福清市| 资阳市| 乌拉特前旗| 兴化市| 堆龙德庆县| 博兴县| 万全县| 阜阳市| 大新县| 阜平县| 平度市| 阳西县| 文昌市| 苗栗市| 邯郸县| 张北县| 乌拉特中旗| 颍上县| 慈溪市| 苏尼特左旗| 南丰县| 仁化县| 涡阳县| 西城区| 平凉市| 富民县| 博罗县| 柳林县| 息烽县| 邹平县| 迁安市| 阳东县| 岚皋县| 天等县|