สร้าง factory method
ถึงเวลาลงมือสร้าง factory method แล้ว! เริ่มต้นด้วยการสร้างคลาส Checkout โดยใช้รูปแบบการออกแบบ factory method อินเทอร์เฟซ Customer ถูกกำหนดไว้ให้แล้ว พร้อมกับ concrete product อย่าง 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}""")
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Object-Oriented Programming ใน Python ระดับกลาง
คำแนะนำการฝึกหัด
- สร้าง factory method ชื่อ
_get_customer()ที่รับพารามิเตอร์customer_typeและ return อ็อบเจกต์ของ concrete product ที่เหมาะสม - ในเมธอด
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 = ____.____(____)
____.____(____)