91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

單例的實現方式

發布時間:2020-06-11 01:05:59 來源:網絡 閱讀:225 作者:qq5a16e6241946e 欄目:編程語言
單例的實現方式:
1、基于類

#encoding=utf-8
class Singleton(object):

    def __init__(self):
        pass

    @classmethod
    def instance(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            Singleton._instance = Singleton(*args, **kwargs)
        return Singleton._instance

s1 = Singleton.instance()
s2 = Singleton.instance()

print(s1 is s2)

支持多線程:
#encoding=utf-8
import threading

class Singleton(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        pass

    @classmethod
    def instance(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):#
            with Singleton._instance_lock:#枷鎖
                if not hasattr(Singleton, "_instance"):
                    Singleton._instance = Singleton(*args, **kwargs)
        return Singleton._instance

def task(arg):
    obj = Singleton.instance()
    print(obj)

for i in range(10):
    t = threading.Thread(target=task,args=(i,))
    t.start()

obj = Singleton.instance()
print(obj)

2、利用__new__()
#encoding=utf-8

class Singleton(object):

    def __init__(self):
        pass

    def __new__(cls,*args,**kwargs):
        if not hasattr(cls,"_instance"):
            cls._instance = object.__new__(cls)
        return cls._instance

p1 = Singleton()
p2 = Singleton()
print(p1 is p2)

支持多線程方式

#encoding=utf-8
import threading

class Singleton(object):

    _instance_lock = threading.Lock()

    def __init__(self):
        pass

    def __new__(cls,*args,**kwargs):
        if not hasattr(cls,"_instance"):
            with cls._instance_lock:
                if not hasattr(cls,"_instance"):
                    cls._instance = object.__new__(cls)
        return cls._instance

def task():
    obj = Singleton()
    print(obj)

for i in range(20):
    t = threading.Thread(target=task,args=())
    t.start()

3、利用裝飾器
#encoding=utf-8
import threading

def Singleton(cls):

    _instance = {}

    def _singleton(*args,**kwargs):
        if cls not in _instance:
            _instance[cls] = cls(*args,**kwargs)
        return _instance[cls]

    return _singleton

@Singleton
class Person(object):#Person = Singleton(Person)
    a =  10

    def __init__(self,x=0):
        self.x = x

p = Person(2)#_singleton(2)
p2 = Person(3)

print(p is p2)

print(p.x)
print(p2.x)

示例1:
#encoding=utf-8
class Person(object):
    __instance = None#定義一個類變量,用于綁定實例對象
    def __init__(self,name,age):
        self.name = name
        self.age = age

    @classmethod
    def get_instance(cls,name,age):
        if cls.__instance == None:
            cls.__instance =Person(name,age)
        return cls.__instance

    def get_info(self):
        return self.name + ":" + str(self.age)

p1 = Person.get_instance("xxx",20)

p2 = Person.get_instance("yyy",50)

print(p1 is p2)

print(p1.get_info())
print(p2.get_info())

#此種實現方式無法在生成實例后改變實例變量的值

示例2:
#encoding=utf-8
class Singleton(object):
    _instance = None

    def __new__(cls,a,b,*args,**kwargs):
        if cls._instance == None:
            cls._instance = super(Singleton,cls).__new__(cls,*args,**kwargs)
        return cls._instance

class Person(Singleton):
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def getInfo(self):
        return "姓名: %s,年齡: %s" %(self.name,self.age)

p1 = Person("張三",20)
print(p1.getInfo())

p2 = Person("李四",20)
print(p1.getInfo())

print(p1 is p2)

print("類變量: ",Person._instance)

示例3:
#encoding=utf-8

class Person(object):

    __instance = None#創建一個類變量用戶存儲類的實例對象

    def __init__(self,name,age):

        self.name = name
        self.age = age

    def __new__(cls,name,age):#自定義Person自己的__new__()方法用于產生實例對象,此處需要傳入name,age兩個參數
        if cls.__instance == None:#保證實例對象__instance只會被賦值一次,如果之前已經創建過實例,直接返回之前創建的實例
            #cls.__instance = super(Person,cls).__new__(cls)
            cls.__instance = object.__new__(cls)#調用父類的__new__方法創建對象

        return cls.__instance#返回實例對象

    def getInfo(self):

        return "姓名: %s,年齡: %s" %(self.name,self.age)

p1 = Person("h",20)
print(p1.getInfo())

p2 = Person("kkk",30)
print(p1.getInfo())
print(p2.getInfo())

print(p1 is p2)

'''
以上代碼執行過程:
p1 = Person("h",20)
首先調用__new__方法產生實例p1,此時Person的__instance為none所以會創建一個對象,
然后調用__init__方法,把返回的實例對象__instance傳入self中,并初始實例變量name,age

print(p2.getInfo())
首先調用__new__方法產生實例p2,此時Person的__instance為不為None,為p1,所以會直接返回對象p1,
然后調用__init__方法,把返回的實例對象__instance傳入self中,并用新的name,age初始實例變量name,age 
'''    

如果__init__有其他參數,__new__需要傳入參數
向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

竹北市| 依兰县| 砀山县| 罗定市| 阜阳市| 乌兰浩特市| 韶关市| 青河县| 茶陵县| 延长县| 高邮市| 万州区| 竹北市| 巴彦县| 临城县| 上栗县| 南靖县| 宁远县| 大竹县| 海口市| 阳新县| 武汉市| 淳安县| 宜兴市| 琼中| 深泽县| 南涧| 西和县| 长葛市| 农安县| 沾益县| 沙洋县| 祁连县| 大庆市| 岚皋县| 许昌市| 横山县| 河北省| 聊城市| 和平县| 正安县|