python 单例模式

2018-09-01 05:53:52来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

单例模式

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

 

单例模式实现方式

方式一:

 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)

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:导师呕心沥血帮我整理出最全Python面试题,学会想不拿offer都难

下一篇:python基础学习8----文件基本操作