始める無料で始める

ファクトリーメソッドを作る

いよいよファクトリーメソッドづくりに取りかかります。まずはファクトリーメソッド・デザインパターンを使って、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 中級オブジェクト指向プログラミング

コースを見る

演習の手順

  • customer_type を取り、適切な具体クラスのオブジェクトを返す _get_customer() ファクトリーメソッドを作成します。
  • complete_transaction() メソッド内で、先ほど定義したファクトリーメソッドを使って顧客オブジェクトを取得し、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 = ____.____(____)
    ____.____(____)
コードを編集して実行