Size: 18
Comment:
|
Size: 1451
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 2: | Line 2: |
== 介绍 == == 创建型模式 == * singleton(单件) * ** 意图 保证一个类仅有一个实例,并提供一个访问它的全局访问点。 ** 实现代码 {{{ #!python class Singleton: """ A python singleton """ class __impl: """ Implementation of the singleton interface """ def spam(self): """ Test method, return singleton id """ return id(self) # storage for the instance reference __instance = None def __init__(self): """ Create singleton instance """ # Check whether we already have an instance if Singleton.__instance is None: # Create and remember instance Singleton.__instance = Singleton.__impl() # Store instance reference as the only member in the handle self.__dict__['_Singleton__instance'] = Singleton.__instance def __getattr__(self, attr): """ Delegate access to implementation """ return getattr(self.__instance, attr) def __setattr__(self, attr, value): """ Delegate access to implementation """ return setattr(self.__instance, attr, value) # Test it s1 = Singleton() print id(s1), s1.spam() s2 = Singleton() print id(s2), s2.spam() # Sample output, the second (inner) id is constant: # 8172684 8176268 # 8168588 8176268 }}} == 结构型模式 == == 行为模式 == |
设计模式
介绍
创建型模式
- singleton(单件) *
- * 意图
- 保证一个类仅有一个实例,并提供一个访问它的全局访问点。
- * 实现代码
1 class Singleton:
2 """ A python singleton """
3
4 class __impl:
5 """ Implementation of the singleton interface """
6
7 def spam(self):
8 """ Test method, return singleton id """
9 return id(self)
10
11 # storage for the instance reference
12 __instance = None
13
14 def __init__(self):
15 """ Create singleton instance """
16 # Check whether we already have an instance
17 if Singleton.__instance is None:
18 # Create and remember instance
19 Singleton.__instance = Singleton.__impl()
20
21 # Store instance reference as the only member in the handle
22 self.__dict__['_Singleton__instance'] = Singleton.__instance
23
24 def __getattr__(self, attr):
25 """ Delegate access to implementation """
26 return getattr(self.__instance, attr)
27
28 def __setattr__(self, attr, value):
29 """ Delegate access to implementation """
30 return setattr(self.__instance, attr, value)
31
32
33 # Test it
34 s1 = Singleton()
35 print id(s1), s1.spam()
36
37 s2 = Singleton()
38 print id(s2), s2.spam()
39
40 # Sample output, the second (inner) id is constant:
41 # 8172684 8176268
42 # 8168588 8176268
结构型模式