欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python 单例模式

程序员文章站 2022-03-20 19:53:58
单例模式 多次实例化的结果指向同一个实例 单例模式实现方式 方式一: 方式二: 方式三: 方式四: ......

单例模式

多次实例化的结果指向同一个实例

 

单例模式实现方式

方式一:

 1 import settings
 2 
 3 class mysql:
 4     __instance = none
 5 
 6     def __init__(self, ip, port):
 7         self.ip = ip
 8         self.port = port
 9 
10     @classmethod
11     def from_conf(cls):
12         if cls.__instance is none:
13             cls.__instance = cls(settings.ip,settings.port)
14         return cls.__instance
15 
16 obj1 = mysql.from_conf()
17 obj2 = mysql.from_conf()
18 obj3 = mysql.from_conf()
19 print(obj1)
20 print(obj2)
21 print(obj3)

 

方式二:

 1 import settings
 2 
 3 def singleton(cls):
 4     _instance = cls(settings.ip, settings.port)
 5 
 6     def wrapper(*args, **kwargs):
 7         if args or kwargs:
 8             obj = cls(*args, **kwargs)
 9             return obj
10         return _instance
11 
12     return wrapper
13 
14 @singleton
15 class mysql:
16     def __init__(self, ip, port):
17         self.ip = ip
18         self.port = port
19 
20 obj1 = mysql()
21 obj2 = mysql()
22 obj3 = mysql()
23 print(obj1)
24 print(obj2)
25 print(obj3)

 

 

方式三:

 1 import settings
 2 
 3 class mymeta(type):
 4     def __init__(self, class_name, class_bases, class_dic):
 5         self.__instance = self(settings.ip, settings.port)
 6 
 7     def __call__(self, *args, **kwargs):
 8         if args or kwargs:
 9             obj = self.__new__(self)
10             self.__init__(obj, *args, **kwargs)
11             return obj
12         else:
13             return self.__instance
14 
15 class mysql(metaclass=mymeta):
16     def __init__(self, ip, port):
17         self.ip = ip
18         self.port = port
19 
20 obj1 = mysql()
21 obj2 = mysql()
22 obj3 = mysql()
23 print(obj1)
24 print(obj2)
25 print(obj3)

 

 

方式四:

 1 def f1():
 2     from singleton import instance
 3     print(instance)
 4 
 5 def f2():
 6     from singleton import instance,mysql
 7     print(instance)
 8     obj = mysql('1.1.1.1', '3389')
 9     print(obj)
10 
11 f1()
12 f2()
13 
14 
15 singleton.py文件里内容:
16 import settings
17 
18 class mysql:
19     print('run...')
20 
21     def __init__(self, ip, port):
22         self.ip = ip
23         self.port = port
24 
25 instance = mysql(settings.ip, settings.port)