LoslegenKostenlos loslegen

Building a factory method

Now that you're ready to get your feet wet building factory methods, you'll start by creating a Checkout class, using the factory method design pattern. The following Customer interface has been defined for you, along with the RewardsMember and NewCustomer concrete products. Check it out below!

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

Diese Übung ist Teil des Kurses

Intermediate Object-Oriented Programming in Python

Kurs anzeigen

Anleitung zur Übung

  • Create a _get_customer() factory method that takes a customer_type, and returns an object of the appropriate concrete product.
  • In the complete_transaction() method, use the previously-defined factory method to return a customer, then, make a payment using the price passed into the make_payment() method.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

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 = ____.____(____)
    ____.____(____)
Code bearbeiten und ausführen