IniziaInizia gratis

Creare un factory method

Ora che sei pronto a mettere le mani in pasta con i factory method, inizierai creando una classe Checkout, usando il design pattern del factory method. L'interfaccia Customer qui sotto è già stata definita per te, insieme ai prodotti concreti RewardsMember e NewCustomer. Dai un'occhiata!

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

Questo esercizio fa parte del corso

Programmazione a oggetti intermedia in Python

Visualizza il corso

Istruzioni dell'esercizio

  • Crea un factory method _get_customer() che prenda un customer_type e restituisca un oggetto del prodotto concreto appropriato.
  • Nel metodo complete_transaction(), usa il factory method definito in precedenza per ottenere un customer, poi effettua un pagamento usando il price passato al metodo make_payment().

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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 = ____.____(____)
    ____.____(____)
Modifica ed esegui il codice