ファクトリーメソッドを作る
いよいよファクトリーメソッドづくりに取りかかります。まずはファクトリーメソッド・デザインパターンを使って、Checkout クラスを作成しましょう。以下には、すでに用意された Customer インターフェースと、具体的なプロダクトである RewardsMember と NewCustomer が定義されています。確認してください。
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 = ____.____(____)
____.____(____)