Python 中的工厂模式
工厂设计模式属于创意设计模式范畴。 创建设计模式提供了许多对象创建技术,从而提高了代码的可重用性和灵活性。
工厂方法是一种创建对象而不指定其具体类的方法。
它以单个父类(抽象类或接口)定义对象的通用结构,而子类提供实例化对象的完整实现的方式提供抽象和多态性。
在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 中工厂方法的缺点
- 我们只能在属于同一类别且特征略有不同的对象时使用它。
- 工厂设计模式增加了代码中类的总数。
- 它降低了代码的可读性,因为由于抽象而隐藏了实现。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串