Python 單例模式實現的五種方式

2021-08-28 03:33:03 字數 3091 閱讀 3295

# 全域性變數

ip = '192.168.13.98'

port = '3306'

class mysql:

__instance = none

def __init__(self, ip, port):

self.ip = ip

self.port = port

@classmethod

def instance(cls, *args, **kwargs):

if args or kwargs:

cls.__instance = cls(*args, **kwargs)

return cls.__instance

obj1 = mysql.instance(ip, port)

obj2 = mysql.instance()

obj3 = mysql.instance()

print(obj1)

print(obj2, obj2.__dict__)

print(obj3, obj3.__dict__)

輸出結果

def singlegon(cls):

_instance = cls(ip, port)

if args or kwargs:

return cls(*args, **kwargs)

return _instance

@singlegon

class mysql1:

def __init__(self, ip, port):

self.ip = ip

self.port = port

obj1 = mysql1()

obj2 = mysql1()

obj3 = mysql1('1.1.1.3', 8080)

print(obj1)

print(obj2, obj2.__dict__)

print(obj3, obj3.__dict__)

執行結果

class mymetaclass(type):

def __init__(self, class_name, class_bases, class_dic):

super().__init__(class_name, class_bases, class_dic)

self.__instance = self(ip, port)

def __call__(self, *args, **kwargs):

if args or kwargs:

obj = self.__new__(self)

self.__init__(obj, *args, **kwargs)

self.__instance = obj

return self.__instance

class mysql2(metaclass=mymetaclass):

def __init__(self, ip, port):

self.ip = ip

self.port = port

obj1 = mysql2()

obj2 = mysql2()

obj3 = mysql2('1.1.1.3', 80)

print(obj1)

print(obj2, obj2.__dict__)

print(obj3, obj3.__dict__)

執行結果

# instance.py

class mysql:

def __init__(self, ip, port):

self.ip = ip

self.port = port

ip = '192.168.13.98'

port = 3306

instance = mysql(ip, port)

# 測試**

import os, sys

from test import instance

obj1 = instance.instance

obj2 = instance.instance

obj3 = instance.mysql('1.1.1.3', 80)

print(obj1)

print(obj2, obj2.__dict__)

print(obj3, obj3.__dict__)

執行結果

class mysql3(object):

__instance = none

__first_init = true

def __init__(self, ip, port):

if self.__first_init:

self.ip = ip

self.port = port

self.__first_init = false

def __new__(cls, *args, **kwargs):

if not cls.__instance:

cls.__instance = object.__new__(cls)

return cls.__instance

obj1 = mysql3(ip, port)

obj2 = mysql3(ip, port)

obj3 = mysql3('1.1.1.3', 80)

print(obj1)

print(obj2, obj2.__dict__)

print(obj3, obj3.__dict__)

執行結果

:前四種可以實現單例模式,但都不是絕對單例模式,可以建立新的物件,但是第五種方式是絕對單例模式,全域性只能真正建立一次物件

五種單例模式實現

public class hunger private final static hunger hunger newhunger public static hunger getinstance 多個執行緒安全,但無法進行懶載入,如果類成員很多,則占用的資源比較多 public class lazy...

單例模式的五種實現

1.1懶漢式,執行緒不安全 單例模式在多執行緒的 應用場合下必須小心使用。如果當唯一例項尚未建立時,有兩個執行緒同時呼叫建立方法,那麼它們同時沒有檢測到唯一例項的存在,從 而同時各自建立了乙個例項,這樣就有兩個例項被構造出來,從而違反了單例模式中例項唯一的原則。解決這個問題的辦法是為指示類是否已經例...

python單例模式的五種實現方式

1.new 特殊方法實現 class singleton def new cls,args,kwargs if nothasattr cls,instance cls.instance super singleton,cls new cls return cls.instance def init ...