1. Học hỏi
  2. /
  3. Khoa Học
  4. /
  5. Lập trình Hướng đối tượng Nâng cao với Python

Connected

Bài tập

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à RewardsMember và NewCustomer. 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}""")

Hướng dẫn

100 XP
  • 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().