栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > Python面试题库

Python如何实现单例模式?其他23种设计模式python如何实现?

Python如何实现单例模式?其他23种设计模式python如何实现?

1 #使用__metaclass__(元类)的高级python用法
2 class Singleton2(type):
3 def __init__(cls, name, bases, dict):
4 super(Singleton2, cls).__init__(name, bases, dict)
5 cls._instance = None
6 def __call__(cls, *args, **kw):
7 if cls._instance is None:
8 cls._instance = super(Singleton2, cls).__call__(*args, **kw)
9 return cls._instance
10
11 class MyClass3(object):
12 __metaclass__ = Singleton2
13
14 one = MyClass3()
15 two = MyClass3()
16
17 two.a = 3
18 print one.a
19 #3
20 print id(one)
21 #31495472
22 print id(two)
23 #31495472
24 print one == two
25 #True
26 print one is two
27 #True
1 #使用装饰器(decorator),
2 #这是一种更pythonic,更elegant的方法,
3 #单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的
4 def singleton(cls, *args, **kw):
5 instances = {}
6 def _singleton():
7 if cls not in instances:
8 instances[cls] = cls(*args, **kw)
9 return instances[cls]
10 return _singleton
11
12 @singleton
13 class MyClass4(object):
14 a = 1
15 def __init__(self, x=0):
16 self.x = x
17
18 one = MyClass4()
19 two = MyClass4()
20
21 two.a = 3
22 print one.a
23 #3
24 print id(one)
25 #29660784
26 print id(two)
27 #29660784
28 print one == two
29 #True
30 print one is two
31 #True
32 one.x = 1
33 print one.x
34 #1
35 print two.x
36 #1

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/266557.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号