单例类

单例类设计模式

常见的设计模式:单例设计模式,工厂设计模式,代理模式,装饰者模式等

单例: 一个类只能创建一个对象

特点:全局唯一,允许更改
优点:节省内存,避免资源重用
缺点:与单一职责冲突,只关心逻辑内部,不管外部结构的变化
应用场景: windows系统的回收站 只能有一个,任务管理器只能打开一个;多线程;连接数据库
 1 # 实现方式1
 2 class Person(object):
 3 __instance = None
 4 
 5 def __new__(cls, *args, **kwargs):
 6 if not cls.__instance: # 如果instance为空
 7 cls.__instance = super().__new__(cls) # 将实例的对象添加到instance里
 8 return cls.__instance # 如果不为空,直接返回instance
 9 
10 def __init__(self,name,age):
11 self.name = name
12 self.age = age
13 
14 
15 p1 = Person('xiaoming',19)
16 p2 = Person('xiaohong',23)
17 print(id(p1),id(p2))
18 
19 print(p1.name)
20 print(p2.name)
21 
22  
23 
24 
25 # 实现方式2(装饰器的方式)
26 def singleton(cls): # cls --> Person
27 instance = None
28 
29 def get_instance(*args, **kwargs):
30 nonlocal instance
31 if not instance:
32 instance = cls(*args, **kwargs)
33 return instance # 调用init
34 return get_instance
35 
36 
37 @singleton
38 class Person(object):
39 def __init__(self,name,age):
40 self.name = name
41 self.age = age
42 
43 
44 p1 = Person('xiaoming',18)
45 p2 = Person('xiaohong',39)
46 print(id(p1),id(p2))
47 
48 
49 # 实现方式3(元类的方式实现单例)
50 class SingletonMeta(type):
51 def __init__(cls,*args,**kwargs):
52 cls.__instance = None
53 super().__init__(*args, **kwargs)
54 
55 def __call__(cls, *args, **kwargs):
56 if cls.__instance is None:
57 cls.__instance = super().__call__(*args,**kwargs)
58 return cls.__instance
59 
60 
61 class Person(metaclass=SingletonMeta):
62 def __init__(self,name):
63 self.name = name
64 
65 
66 p1 = Person('xiaoming')
67 p2 = Person('xiaohong')
68 print(p1.name)
69 print(p2.name)

 



posted @ 2022-06-01 16:15  目光所至皆是你  阅读(46)  评论(0)    收藏  举报