What template with branching schemes have you used in practice?
sobes.tech AI
Answer from AI
In Python programming practice, templates with branching application schemes are often used, for example:
-
Strategy Pattern: allows selecting an algorithm from a set of options at runtime. Branching occurs when choosing a specific strategy.
-
State Pattern: an object changes its behavior depending on its internal state, which is implemented through branching by states.
-
Event Handlers: different actions are performed depending on the type or content of the event.
-
Chain of Responsibility: a request is passed along a chain of handlers, each deciding whether to handle the request or pass it further.
Example of using the "Strategy" pattern:
class PaymentStrategy:
def pay(self, amount):
pass
class CreditCardPayment(PaymentStrategy):
def pay(self, amount):
print(f"Paying {amount} with a credit card")
class PayPalPayment(PaymentStrategy):
def pay(self, amount):
print(f"Paying {amount} via PayPal")
class ShoppingCart:
def __init__(self, payment_strategy):
self.payment_strategy = payment_strategy
def checkout(self, amount):
self.payment_strategy.pay(amount)
# Usage
cart = ShoppingCart(CreditCardPayment())
cart.checkout(100)
cart.payment_strategy = PayPalPayment()
cart.checkout(200)
This approach allows flexible changes to the program's behavior without altering its structure.