迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中的工厂模式

作者:迹忆客 最近更新:2023/07/02 浏览次数:

工厂设计模式属于创意设计模式范畴。 创建设计模式提供了许多对象创建技术,从而提高了代码的可重用性和灵活性。

工厂方法是一种创建对象而不指定其具体类的方法。

它以单个父类(抽象类或接口)定义对象的通用结构,而子类提供实例化对象的完整实现的方式提供抽象和多态性。


在Python中实现工厂方法

在下面的代码中,abc是一个代表抽象基类的包,我们从中导入了ABCMeta(用于声明抽象类)和abstractstaticmethod(用于声明抽象静态方法)。

我们定义了一个名为 Person 的通用抽象基类,具有一个抽象静态方法 person_type()。

具体的派生类将实现此方法。 然后我们从 Person 定义了两个派生类,分别名为 Student 和 Teacher。 这两个类都根据需要实现了抽象静态方法 person_type()。

我们声明了工厂方法 PersonFactory 负责在运行时根据用户的输入选择创建 Person 的对象(学生或教师)。

该类有一个静态方法 build_person(),它将 person 类型作为参数,并使用其名称(学生姓名或教师姓名)构造所需的对象。

示例代码:

#Python 3.x
from abc import ABCMeta, abstractstaticmethod
class Person(metaclass=ABCMeta):
    @abstractstaticmethod
    def person_type():
        pass
class Student(Person):
    def __init__(self, name):
        self.name=name
        print("Student Created:", name)
    def person_type(self):
        print("Student")
class Teacher(Person):
    def __init__(self, name):
        self.name=name
        print("Teacher Created:", name)
    def person_type(self):
        print("Teacher")
class PersonFactory:
    @staticmethod
    def build_person(person_type):
        if person_type == "Student":
            name=input("Enter Student's name: ")
            return Student(name)
        if person_type == "Teacher":
            name=input("Enter Teacher's name: ")
            return Teacher(name)
if __name__== "__main__":
    choice=input("Enter the Person type to create: ")
    obj=PersonFactory.build_person(choice)
    obj.person_type()

输出:

#Python 3.x
Enter the Person type to create: Teacher
Enter Teacher's name: Jhon
Teacher Created: Jhon
Teacher

Python 中工厂方法的优点

  • 它促进代码中的松散耦合。
  • 可以很容易地修改代码以实例化具有稍微不同特征的新对象,而不会干扰当前代码。
  • 它促进代码中的抽象和多态性。

Python 中工厂方法的缺点

  • 我们只能在属于同一类别且特征略有不同的对象时使用它。
  • 工厂设计模式增加了代码中类的总数。
  • 它降低了代码的可读性,因为由于抽象而隐藏了实现。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便