單列模式 實現單列模式的五種方法

2021-09-23 06:17:18 字數 2843 閱讀 2383

何為單列模式

不管例項化你建立多少的物件,我只給你們返回的總是哪乙個

第一種:通過類方法實現
class

mysql

(object):

_instance =

none

def__init__

(self, ip, port)

: self.ip = ip

self.port = port

@classmethod

defsingleton

(cls):if

not cls._instance:

cls._instance = mysql(

'127.0.0.1'

,3306

)return cls._instance

if __name__ ==

'__main__'

: obj1 = mysql.singleton(

) obj2 = mysql.singleton(

)print

(obj1)

print

(obj2)

第二種:通過裝飾器實現
def

singleton

(cls)

: _instance = cls(

'127.0.0.1'

,3306

)def

inner

(*args,

**kws)

:if args or kws:

return cls(

*args,

**kws)

return _instance

return inner

@singleton

class

mysql

(object):

def__init__

(self, ip, port)

: self.ip = ip

self.port = port

if __name__ ==

'__main__'

: obj1 = mysql(

) obj2 = mysql(

)print

(obj1)

print

(obj2)

第三種:通過元類實現
class

mymetaclass

(type):

def__call__

(self,

*args,

**kws):if

nothasattr

(self,

'instance'):

self.instance =

super()

.__call__(

*args,

**kws)

return self.instance

class

mysql

(metaclass=mymetaclass)

:def

__init__

(self, ip, port)

: self.ip = ip

self.port = port

if __name__ ==

'__main__'

: obj1 = mysql(

'127.0.0.1'

,3306

) obj2 = mysql(

'127.0.0.1'

,3308

)print

(obj1)

print

(obj2)

第四種:通過 __new__方法實現
class

singleton

(object):

_instance =

none

def__new__

(cls,

*args,

**kws):if

not cls._instance:

cls._instance =

super()

.__new__(cls,

*args,

**kws)

return cls._instance

class

mysql

(singleton)

:def

__init__

(self)

: self.ip =

'127.0.0.1'

self.port =

3306

if __name__ ==

'__main__'

: obj1 = mysql(

) obj2 = mysql(

)print

(obj1)

print

(obj2)

第五種:通過模組來實現

sing.py

class

mysql

(object):

def__init__

(self, ip, port)

: self.ip = ip

self.port = port

mysqlsingleton = mysql(

'127.0.0.1'

,2206

)

sql.py

from sing import mysqlsingleton

單列模式幾種方法分析

方法一 懶漢式 懶漢式對於單執行緒而言,推薦使用,但是對於多執行緒,可能會出現 資料不同步,也可能會建立出好幾個物件,因此不建議使用 public class singlemodeltwo 執行緒不安全 return public static singlemodeltwo getinstance ...

六種單列模式

確保某乙個類只有乙個例項.1 餓漢式單列 public class singleone 構造方法私有 禁止建立 private singleone 2 懶漢式單列 public class singletwo 同步方法 每次呼叫都同步 消耗資源 public static synchronized ...

Python 裝飾器實現單列模式

使用裝飾器實現單列模式 defsingleton cls 用來存在例項的字典 singleton instance 判斷字典中是否例項 ifnot singleton instance.get cls.name 沒有則建立乙個例項,並存入字典中 singleton instance cls.name...