Design patterns in Python-single case

05bd1583c87cbb790d6cb4c544bf1c0c.png

Lost little book boy

Needed after reading

2

minute

Speed ​​reading only takes 1 minute

When we talk about the singleton pattern, we can imagine a very special restaurant. This restaurant has only one table. No matter how many people come to dine, they can only sit on this table. This table is a single instance of the restaurant, which ensures that only one table exists in the entire restaurant.

In Python, the singleton pattern is used to ensure that a class has only one instance and provides a global access point to that instance. This is useful in certain situations, such as where you need to share resources or share state across multiple objects.

Let us understand the principles of singleton pattern through an example. Suppose we have a class called Database that represents a database connection. We want to have only one database connection instance in the entire application.

class Database:
    _instance = None


    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

In this example, we use the special method __new__ in Python to control the object creation process. The __new__ method is called before the object is instantiated and is responsible for creating and returning an instance of the object.

In the Database class, we use a class variable _instance to hold the unique instance. In the __new__ method, we check if _instance is None, if so, create a new instance and assign it to _instance, otherwise return the existing instance directly.

Now, no matter where in the code we create the Database object, the same instance will be returned

db1 = Database()
db2 = Database()


# 输出: True
print(db1 is db2)

This is because the __new__ method of the Database class ensures that only one instance exists. No matter how many Database objects we create, they all point to the same instance.

Through this metaphor and code example, we can better understand the principles of the singleton pattern. It ensures that only one instance exists in the entire application, just like there is only one table in a restaurant.

It should be noted that the singleton pattern is not a panacea and may lead to global state and tightly coupled code. Therefore, when using the singleton pattern, you need to carefully consider its suitability and ensure that it meets the design requirements.

428e33398fe73d38ff4996374487488b.jpeg

e31a63a8a2af7a319b98506ff7da8c02.gif

Guess you like

Origin blog.csdn.net/djstavaV/article/details/133257807