博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python工厂模式

Posted on 2023-08-08 10:29  steve.z  阅读(10)  评论(0编辑  收藏  举报
#
#   py_factory.py
#   py_learn
#
#   Created by Z. Steve on 2023/8/8 10:17.
#


# 工厂模式优点:
# 1. 大批量创建对象是, 有统一的入口, 易于代码维护。
# 2. 当发生修改时,只需要修改工厂类的创建方法即可
# 3. 符合现实世界的模式,即由工厂来制作产品(对象)


class Person:
    pass


class Student(Person):
    pass


class Teacher(Person):
    pass


class Doctor(Person):
    pass


class Factory:
    def create_person(self, type):
        if type == 's':
            return Student()
        elif type == 't':
            return Teacher()
        else:
            return Doctor()


# 1. 创建一个工厂对象
factory = Factory()

# 2. 通过工厂对象创建对象
teacher = factory.create_person('t')
student = factory.create_person('s')
doctor = factory.create_person('d')