■ 单例模式
- 新建文件 str_tools.py 如下代码。
class StrTools:
pass
str_tool = StrTools()
- 在其他文件使用时导入该变量。
from str_tools_py import str_tool
s1 = str_tool
s2 = str_tool
print(id(s1))
print(id(s2))
■ 工厂模式
"""
演示设计模式之工厂模式
"""
class Person:
pass
class Worker(Person):
pass
class Student(Person):
pass
class Teacher(Person):
pass
class PersonFactory:
def get_person(self, p_type):
if p_type == 'w':
return Worker()
elif p_type == 's':
return Student()
else:
return Teacher()
pf = PersonFactory()
worker = pf.get_person('w')
stu = pf.get_person('s')
teacher = pf.get_person('t')
- 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
■
■