亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

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

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

單例的實現方式

發布時間: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

文山县| 汾阳市| 淮南市| 诸城市| 滦平县| 中阳县| 秀山| 美姑县| 乌兰县| 新营市| 北海市| 淅川县| 邢台市| 温泉县| 黑水县| 青浦区| 南华县| 阿合奇县| 济源市| 曲沃县| 衡南县| 永善县| 内丘县| 临城县| 乌拉特后旗| 汾阳市| 玉山县| 德安县| 北安市| 金湖县| 乌拉特后旗| 金乡县| 正阳县| 珲春市| 安丘市| 伊川县| 博兴县| 保德县| 丽江市| 余江县| 前郭尔|