python–设计模式–02–工厂模式
1、介绍
使用工厂类对象来创建所需要的对象
1.1、扩展
https://blog.csdn.net/zhou920786312/article/details/82958242
2、代码
"""
工厂模式
"""
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()
if __name__ == '__main__':
# 创建工厂
pf = PersonFactory()
# 通过工厂获取 worker对象
worker = pf.get_person('w')
# 通过工厂获取 Student对象
stu = pf.get_person('s')
# 通过工厂获取 teacher对象
teacher = pf.get_person('t')