banner
Oct 7, 2023
206 Views

Template method pattern

Written by
banner

The template method pattern là một phương thức trong một lớp cha xác định cấu trúc cơ bản của một hoạt động dưới dạng một loạt các bước ở mức cao. Những bước này được thực hiện bởi các phương thức trợ giúp bổ sung trong cùng một lớp như phương thức mẫu.

The template method is a method in a superclass, usually an abstract superclass, and defines the skeleton of an operation in terms of a number of high-level steps. These steps are themselves implemented by additional helper methods in the same class as the template method.

Ví dụ bạn làm 1 phần mềm pha đồ uống tự động có thể pha trà và cà phê. Các bước hầu hết khác nhau nhưng đều có bước đun nước và đổ vào cốc là như nhau

from abc import ABC, abstractmethod

# Abstract class defining the template method for preparing beverages
class BeverageTemplate(ABC):

    def prepare_beverage(self):
        self.boil_water()
        self.brew()
        self.pour_in_cup()
        self.add_condiments()

    def boil_water(self):
        print("Boiling water")

    @abstractmethod
    def brew(self):
        pass

    def pour_in_cup(self):
        print("Pouring into cup")

    @abstractmethod
    def add_condiments(self):
        pass

# Concrete class for making coffee
class Coffee(BeverageTemplate):

    def brew(self):
        print("Dripping coffee through filter")

    def add_condiments(self):
        print("Adding sugar and milk")

# Concrete class for making tea
class Tea(BeverageTemplate):

    def brew(self):
        print("Steeping the tea")

    def add_condiments(self):
        print("Adding lemon")

def main():
    print("Making Coffee:")
    coffee = Coffee()
    coffee.prepare_beverage()

    print("\nMaking Tea:")
    tea = Tea()
    tea.prepare_beverage()

if __name__ == "__main__":
    main()
Article Categories:
dev
banner

Leave a Reply

Your email address will not be published. Required fields are marked *