Python Singleton Pattern (singleton)

Brief introduction

Singleton (Singleton Pattern) is a common software design pattern, the main purpose of this mode is to ensure that only one instance of a particular class exists. When you want in the whole system, can appear only one instance of a class, singleton objects can come in handy.
When the static value of a class called repeatedly wasteful, embodiment mode can be implemented on a single

achieve

principle

Example:

class Foo(object):
    instance = None

    def __init__(self):
        pass

    @classmethod
    def get_instance(cls, *args, **kwargs):
        if Foo.instance:
            return Foo.instance
        else:
            Foo.instance = Foo(*args, **kwargs)
            return Foo.instance


obj1 = Foo.get_instance()
obj2 = Foo.get_instance()
print(obj1, obj2)

Note: This will result in changes in the way an object is created, so using the following method

By class implementation

Example:

class Foo(object):
    instance = None

    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if Foo.instance:
            return Foo.instance
        else:
            Foo.instance = object.__new__(cls, *args, **kwargs)
            return Foo.instance


obj1 = Foo()
obj2 = Foo()
print(obj1, obj2)

Since the generated class calling sequence is: new new -> the init -> Call
so that the first method is called __new__

Guess you like

Origin www.cnblogs.com/dbf-/p/10991960.html