The Object Oriented singleton

Example 1. Single Mode

1.1 What is a singleton

  • Based exemplary embodiment is single-mode multiple times to give some examples of the method is the same
class Foo():
    def __init__(self,name, age):
        self.name = name
        self.age = age
        
f1 = Foo('hades',13)
print(f1)
f2 = Foo('hades',13)
print(f2)
f3 = Foo('hades',13)
print(f3)
<__main__.Foo object at 0x0000023CB56AD518>
<__main__.Foo object at 0x0000023CB56AD550>
<__main__.Foo object at 0x0000023CB5688048>

Demonstrated above embodiment does not belong to a single mode, although it looks exactly the same instance of an object, but the memory address can be seen, in fact, are separate objects

1.2 Why singleton

  • When times get instantiated object attributes are stored in the same time, we have no need to take up more memory space, instantiate an object point to the same memory

  • The ultimate goal is to save memory

1.3 singleton three ways

The method of using the binding characteristics 1.3.1 Internal class, static methods defined

NAME = 'hades'
AGE = 27

class People:
    __instance = None
    
    def __init__(self,name,age):
        self.name = name 
        self.age = age
        
    @classmethod
    def from_conf(cls):
        if cls.__instance:
            return cls.__instance
        
        cls.__instance = People.__init__(cls,NAME,AGE)
        return cls.__instance
        
p1 = People.from_conf()
p2 = People.from_conf()
print(p1==p2)
True

1.3.2 embodiment using single-mode decorator

NAME = 'hades'
AGE = 27

def deco(cls):
    cls.__instance = cls(NAME,AGE)
    
    def wrapper(*args,**kwargs):
        if len(args) == 0 and len(kwargs) == 0:
            return cls.__instance
        
        res = cls(*args,**kwargs)
        return res
    
    return wrapper

@deco
class People():
    
    def __init__(self,name,age):
        self.name = name
        self.age = age
        
p1 = People()
p2 = People()
p3 = People('bonnie',16)
print(p1 == p2)
print(p1 == p3)
True
False

1.3.3 embodiment using single-mode metaclass

NAME = 'hades'
AGE = 27

class Mymeta(type):
    def __init__(self, class_name, class_bases, class_dict):
        super().__init__(class_name, class_bases, class_dict)
        
        self.__instance = self(NAME, AGE)
        
    def __call__(self, *args, **kwargs):
        
        if len(args) == 0 and len(kwargs) == 0:
            return self.__instance
        
        obj = self.__new__(self)
        self.__init__(obj, *args, **kwargs)
        
        return obj
        
class People(metaclass=Mymeta):
    def __init__(self,name,age):
        self.name = name
        self.age = age
        
p1 = People()
p2 = People()
p3 = People('bonnie',16)
print(p1 == p2)
print(p1 == p3)
True
False

Guess you like

Origin www.cnblogs.com/Hades123/p/11068357.html