概念解析
顾名思义,单例模式,指的便是:希望类只能有一个实例,通常应用于一些全局管理器。
设计模板
以下展示三种不同的单例模式的实现方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Singleton1(object):
"单例实现方式一:基本实现"
__instance = None
__isFirstInit = False
def __new__(cls, name):
if not cls.__instance:
Singleton1.__instance = super().__new__(cls)
return cls.__instance
def __init__(self, name):
if not self.__isFirstInit:
self.__name = name
Singleton1.__isFirstInit = True
def getName(self):
return self.__name
class Singleton2(type):
"单例实现方式二:metaclass"
def __init__(cls, what, bases=None, dict=None):
super().__init__(what, bases, dict):
cls._instance = None # 初始化全局变量cls._instance为None
def __call__(cls, *args, **kwargs):
# 控制对象的创建过程,如果cls._instance为None,则创建,否则直接返回
if cls._instance is None:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
class CustomClass(metaclass=Singleton2):
"用户自定义的类"
def __init__(self, name):
self.__name = name
def getName(self):
return self.__name
def singletonDecorator(cls, *args, **kwargs):
"单例实现方式三:装饰器"
instance = {}
def wrapperSingletone(*args, **kwargs):
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return wapperSigleton
@singleDecorator
class Singleton3:
"单列装饰器修饰类"
def __init__(self, name):
self.__name = name
def getName(self):
return self.__name
实例分析
简单样例:
1
2
3
4
5
6
7
8
9
10
11
12
13
@singletonDecorator
class MyBeautifulGirl(object):
"唯一女神"
def __init__(self, name):
self.__name = name
if self.__name == name:
print("遇见" + name + ", 我一见钟情!")
else:
print("遇见" + name + ", 我置若罔闻!")
def showMyHeart(self):
print(self.__name + "就是我的唯一!")