A general implementation of the singleton pattern

The hungry type

Slacker style is a way to implement singletons, which I don’t use very often, so I’ll write a hungry style here. I’ll fix it later. The core role of the singleton pattern is to ensure that a class has only one object of that type. To avoid consuming too much memory when an object is called too many times, you can use the singleton pattern.

Creating a new object in Python calls the __new__ method to allocate its memory space for the created object and returns a reference to the object, which is then passed to the __init__ function for instantiation.

In general, you do not need to call the new method; this step is necessary when using singletons. When overriding a new method, we need to return the class CLS of the current instance: return super().__new__(CLS). Once the allocated memory space is referenced, instantiate the object. The code can be simply written as follows:

class ClassObj(object):
    def __new__(cls):
        print("Allocate memory")
        return super().__new__(cls)

    def __init__(self):
        print("Start initialization")
cobj = ClassObj()
Copy the code

The running results are as follows:

new

class ClassObj(object):
    instance=None
    def __new__(cls):
        if cls.instance is None:
            cls.instance=super().__new__(cls)
            print("Allocate memory")
        else:
            print("Already assigned.")
        return cls.instance

    def __init__(self):
        print("Already assigned.")
cobj = ClassObj()
cobj1 = ClassObj()
Copy the code

This code defines a member variable instance in the ClassObj that stores the allocated space reference and returns instance in the __new__ method. If instance is None, the system instantiates the object for the first time. If instance is not None, the system prompts that space has already been allocated and will not allocate space again. The running results are as follows:

cobj = ClassObj()
cobj1 = ClassObj()
print(cobj)
print(cobj1)
Copy the code

The result is the same as follows: