0%

Python设计模式

1 单例模式

核心思想

主要是应用于全局变量,例如日志生成器logger,全局应只定义一个。

实现方法是重写类内置函数new(cls),不进行新的创建,同时利用内部私有类存储方法和属性。

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class SingletonObject(object):
class __SingletonObject():
def __init__(self):
self.val = None
def __str__(self):
return "{0!r} {1}".format(self, self.val)

instance = None
def __new__(cls):
if not SingletonObject.instance:
SingletonObject.instance = SingletonObject.__SingletonObject()
return SingletonObject.instance

def __getattr__(self, name):
return getattr(self.instance, name)

def __setattr__(self, name):
return setattr(self.instance, name)

2 原型模式

核心思想

建立实例时,防止频繁读取配置文件

Example

prototype_1.py

1
2
3
4
5
from abs import ABCMeta, abstractmethod
class Prototype(metaclass=ABCMeta):
@abstractmethod
def clone(self):
pass

concrete.py

1
2
3
4
5
from prototype_1 import Prototype
from copy import deepcopy
class Concrete(Prototype):
def clone(self):
return deepcopy(self)

rts_prototype.py

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
from prototype_1 import Prototype
from copy import deepcopy
class Knight(Prototype):
def __init__(self, level):
self.unit_type = "Knight"
filename = "{}_{}.bat".format(self.unit_type, level)
with open(filename, 'r') as parameter_file:
pass
def __str__(self):
pass
def clone(self):
return deepcopy(self)

class Archer(Prototype):
def __init__(self, level):
self.unit_type = "Archer"
filename = "{}_{}.bat".format(self.unit_type, level)
with open(filename, 'r') as parameter_file:
pass
def __str__(self):
pass
def clone(self):
return deepcopy(self)

class Barracks(object):
def __init__(self):
self.units = {
"knight": {
1: Knight(1),
2: Knight(2)
},
"archer": {
1: Archer(1),
2: Archer(2)
}
}
def build_unit(self, unit_type, level):
return self.units[unit_type][level].clone()

3 工厂模式

Reference

  • 《Python设计模式》, [美]Wessel Badenhorst;蒲成译,清华大学出版社,2019
Have fun.