Python中的工厂模式

工厂设计模式是属于创造型设计模式的范畴。创造性设计模式为对象的创建提供了许多技术,从而使代码具有更多的可重用性和灵活性。

工厂方法是一种创建对象的方法,无需指定其具体类别。

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

在Python中实现工厂方法

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

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

具体的派生类将实现这个方法。然后我们从Person 中定义了两个派生类,名为StudentTeacher 。这两个类根据自己的需要实现抽象静态方法person_type()

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

这个类有一个静态方法,build_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中工厂方法的优点

  • 它促进了代码中的loose coupling
  • 在不影响当前代码的情况下,很容易修改代码来实例化具有轻微不同特征的新对象。
  • 它在代码中促进了abstractionpolymorphism

Python中工厂方法的缺点

  • 我们只能在对象属于同一类别但特征略有不同的情况下使用它。
  • 工厂设计模式增加了代码中类的总数。
  • 它减少了代码的readability ,因为由于抽象,实现被隐藏了。