工厂方法

Python 面向对象编程进阶

Jake Roach

Data Engineer

方法中的条件逻辑

class Student:
    # 在一个方法中使用条件分支,且各分支行为相似
    def explore_topic(self, resource_type, topic):
        if resource_type == "Textbook":
            print(f"使用教材查阅 {topic}")
            self.reference_textbook(topic)

        elif resource_type == "Blog":
            print(f"务必核实博客中的信息!")
            self.reference_blog(topic)

        elif resource_type == "Video":
            self.reference_video(topic)
Python 面向对象编程进阶

工厂方法

一种设计模式:用工厂方法创建对象,并在其他方法中使用

  • 返回实现同一接口的对象
  • 降低方法复杂度
  • 可复用,模块化
  • _ 标注工厂方法

$$

首先看看产品与具体产品!

...

  def _get_resource(self, resource_type):  
    if resource_type == "Textbook":
      # Textbook、Blog 和 Video 都是
      # 资源
      return Textbook()  

    elif resource_type == "Blog":
      return Blog()  

    elif resource_type == "Video":
      return Video()
Python 面向对象编程进阶

创建 Resource 接口

class Resource(ABC):
    @abstractmethod
    def reference(self, topic):
        pass
class Textbook(Resource):
    def __init__(self):
        self.index = {"Object-oriented Programming": ["Inheritance", ...]}

    def reference(self, topic):
        print(f"使用教材查阅 {topic}")
        return self.index.get(topic)

# Blog、Video 类似
Python 面向对象编程进阶

重构 explore_topic()

class Student:

    def explore_topic(self, resource_type, topic):
        if resource_type == "Textbook":
            texbook = Textbook()  # 创建实现 Resource 的实例
            texbook.reference(topic)  # 调用 reference()

        elif resource_type == "Blog":
            blog = Blog()
            blog.reference(topic)

        elif resource_type == "Video":
            video = Video()
            video.reference(topic)
Python 面向对象编程进阶

创建工厂方法

class Student:
    # 工厂方法:返回 Resource
    def _get_resource(self, resource_type):
        if resource_type == "Textbook":
            return Textbook()  
        elif resource_type == "Blog":
            return Blog()  
        elif resource_type == "Video":
            return Video()

    def explore_topic(self, resource_type, topic):
        resource = self._get_resource(resource_type)  # 获取资源
        return resource.reference(topic)
Python 面向对象编程进阶

使用工厂方法

# 创建一个 Student 对象,然后引用教材
lester = Student()
lester.explore_topic("Textbook", "Object-oriented Programming")

# 轻松切换到其他资源
lester.explore_topic("Video", "Object-oriented Programming")
使用教材查阅 Object-oriented Programming
["Inheritance", "Constructors", "Class-level methods"]

视频有助于视觉或听觉型学习者
["Classes", "Methods", "Attributes", "self"]
Python 面向对象编程进阶

Ayo berlatih!

Python 面向对象编程进阶

Preparing Video For Download...