Phương thức factory

Lập trình Hướng đối tượng Nâng cao với Python

Jake Roach

Data Engineer

Logic điều kiện trong một phương thức

class Student:
    # Logic điều kiện với hành vi tương tự cho mọi nhánh
    def explore_topic(self, resource_type, topic):
        if resource_type == "Textbook":
            print(f"Tham chiếu {topic} bằng sách giáo khoa")
            self.reference_textbook(topic)

        elif resource_type == "Blog":
            print(f"Hãy xác thực thông tin trong blog!")
            self.reference_blog(topic)

        elif resource_type == "Video":
            self.reference_video(topic)
Lập trình Hướng đối tượng Nâng cao với Python

Phương thức factory

Mẫu thiết kế dùng factory method để tạo đối tượng cho phương thức khác sử dụng

  • Trả về đối tượng triển khai một interface
  • Giảm độ phức tạp của phương thức
  • Tái sử dụng, mô-đun hóa
  • Dùng _ để ký hiệu factory method

$$

Trước hết, hãy xem sản phẩm và sản phẩm cụ thể!

...

  def _get_resource(self, resource_type):  
    if resource_type == "Textbook":
      # Textbook, Blog và Video đều là
      # resource
      return Textbook()  

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

    elif resource_type == "Video":
      return Video()
Lập trình Hướng đối tượng Nâng cao với Python

Tạo interface 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"Tham chiếu {topic} bằng sách giáo khoa")
        return self.index.get(topic)

# Tương tự cho Blog, Video
Lập trình Hướng đối tượng Nâng cao với Python

Viết lại explore_topic()

class Student:

    def explore_topic(self, resource_type, topic):
        if resource_type == "Textbook":
            texbook = Textbook()  # Tạo instance của lớp triển khai Resource
            texbook.reference(topic)  # Gọi phương thức reference()

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

        elif resource_type == "Video":
            video = Video()
            video.reference(topic)
Lập trình Hướng đối tượng Nâng cao với Python

Tạo một factory method

class Student:
    # Factory method để trả về 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)  # Lấy resource
        return resource.reference(topic)
Lập trình Hướng đối tượng Nâng cao với Python

Dùng factory method

# Tạo đối tượng Student, rồi tham chiếu một textbook
lester = Student()
lester.explore_topic("Textbook", "Object-oriented Programming")

# Dễ dàng chuyển sang resource khác
lester.explore_topic("Video", "Object-oriented Programming")
Tham chiếu Object-oriented Programming bằng sách giáo khoa
["Inheritance", "Constructors", "Class-level methods"]

Video hữu ích cho người học trực quan hoặc thính giác
["Classes", "Methods", "Attributes", "self"]
Lập trình Hướng đối tượng Nâng cao với Python

Ayo berlatih!

Lập trình Hướng đối tượng Nâng cao với Python

Preparing Video For Download...