Bắt đầu ngayBắt đầu miễn phí

Xây dựng một factory method

Giờ bạn đã sẵn sàng bắt tay vào xây dựng factory methods. Hãy bắt đầu bằng cách tạo lớp Checkout theo mẫu thiết kế factory method. Giao diện Customer sau đã được định nghĩa sẵn cho bạn, cùng với hai concrete product là RewardsMemberNewCustomer. Xem bên dưới!

class Customer(ABC):
  @abstractmethod
  def make_payment(self, price):
    pass

class RewardsMember(Customer):
  def make_payment(self, price):
    print(f"""Total price for rewards member is 
          ${price * .90}, which is 10% off""")

class NewCustomer(Customer):
  def make_payment(self, price):
    print(f"""Total price for new customer is ${price}""")

Bài tập này là một phần của khóa học

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

Xem khóa học

Hướng dẫn bài tập

  • Tạo một factory method _get_customer() nhận customer_type và trả về một đối tượng của concrete product phù hợp.
  • Trong phương thức complete_transaction(), sử dụng factory method đã định nghĩa trước đó để trả về một customer, sau đó thực hiện thanh toán bằng cách truyền price vào phương thức make_payment().

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

class Checkout:
  # Create a _get_customer() factory method 
  def ____(self, customer_type):
    if ____ == "Rewards Member":
      return ____()
    elif ____ ____ "New Customer":
      return ____()
  
  # Define the complete_transaction() method
  def complete_transaction(self, customer_type, price):
    customer = ____.____(____)
    ____.____(____)
Chỉnh sửa và Chạy Mã