建立 factory method
既然你已經準備好動手實作 factory method,先從建立一個 Checkout 類別開始,並使用 factory method 設計模式。下面已經為你定義好 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 物件導向程式設計進階
練習說明
- 建立一個
_get_customer()factory method,接收customer_type,並回傳對應之具體產品的物件。 - 在
complete_transaction()方法中,使用前面定義的 factory method 取得顧客物件,接著用傳入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 = ____.____(____)
____.____(____)