python 单例模式
2021-07-12 07:05
标签:ase self ... init python col war imp code 单例模式 多次实例化的结果指向同一个实例 单例模式实现方式 方式一: 方式二: 方式三: 方式四: python 单例模式 标签:ase self ... init python col war imp code 原文地址:https://www.cnblogs.com/hades0607/p/9548684.html 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)