开始使用免费开始使用

构建一个工厂方法

现在,您已经准备好上手实现工厂方法了。请从创建一个 Checkout 类开始,并使用工厂方法设计模式。下面已为您定义好了 Customer 接口,以及 RewardsMemberNewCustomer 这两个具体产品。请先看看下面的代码!

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}""")

本练习是课程的一部分

Python 面向对象编程进阶

查看课程

练习说明

  • 创建一个 _get_customer() 工厂方法,接收 customer_type,并返回相应具体产品的对象。
  • complete_transaction() 方法中,使用前面定义的工厂方法返回一个 customer,然后使用传入 make_payment()price 完成支付。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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 = ____.____(____)
    ____.____(____)
编辑并运行代码