单例模式:一个类无论实例化多少次,返回的都是同一个实例,例如:a1=A(), a2=A(), a3=A(),a1、a2和a3其实都是同一个对象,即print(a1 is a2)和print(a2 is a3)都会打印True。
实现方式:有两种方式,一种是使用元类metaclass控制类实例化时的对象,另一种是使用类的__new__方法控制类返回的对象,推荐使用元类的方式,因为__new__通常是用来改变类结构的。
注:关于元类和单例模式,本文只是贴了两个简单的示例代码和自己的一些心得,想要更加深入的学习,这里有一篇博客讲得很详细https://www.cnblogs.com/tkqasn/p/6524879.html
元类实现单例模式(Python3.6):
1 class Singleton(type):
2 def __init__(cls, *args, **kwargs):
3 cls.__instance = None
4 super().__init__(*args, **kwargs)
5
6 def __call__(cls, *args, **kwargs):
7 if cls.__instance is None:
8 cls.__instance = super().__call__(*args, **kwargs)
9
10 return cls.__instance
11
12
13 class MySingleton(metaclass=Singleton):
14 def __init__(self, val):
15 self.val = val
16 print(self.val)
17
18
19 hello = MySingleton('hello')
20 hi = MySingleton('hi')
21 print(hello is hi)
22
23 ----------输出结果----------
24 hello
25 True
__new__实现单例模式(Python3.6):
1 class MySingleton:
2 def __init__(self, val):
3 self.val = val
4 print(self.val)
5 print(self.__dict__)
6
7 def __new__(cls, *args, **kwargs):
8 if not hasattr(cls, '_instance'):
9 cls._instance = super().__new__(cls)
10
11 return cls._instance
12
13
14 hello = MySingleton('hello')
15 hi = MySingleton('hi')
16 print(hello is hi)
17
18
19 -----------输出结果--------------
20 hello
21 {'val': 'hello'}
22 hi
23 {'val': 'hi'}
24 True