Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
Observer, Strategy, and Command
Observer, Strategy, CommandSubject
e.g. WeatherStation
Observer
e.g. Phone display
Observer
e.g. Computer display
GUI, user interactions)MVC, MVP, MVVM)class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def notify(self, message):
for observer in self._observers:
observer.update(message)
class WeatherStation(Subject):
@property
def temperature(self):
return self._temperature
@temperature.setter
def temperature(self, temp):
self._temperature = temp
self.notify(f"Temperature changed to {temp}")Context
e.g. ShoppingCart
Strategy
CreditCardPayment
Strategy
PayPalPayment
class CreditCardPayment(PaymentStrategy):
def pay(self, amount):
return f"Paid ${amount} by Credit Card"
class PayPalPayment(PaymentStrategy):
def pay(self, amount):
return f"Paid ${amount} by PayPal"
cart.set_payment_strategy(CreditCardPayment())
print(cart.checkout())Invoker
e.g. RemoteControl
Command
e.g. LightOnCommand
Receiver
e.g. Light
class LightOnCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
return self.light.turn_on()
def undo(self):
return self.light.turn_off()
remote.set_command(1, LightOnCommand(living_room_light))
remote.press_button(1) # Living Room light is ON
remote.press_undo() # Living Room light is OFFif/else chainsMahmoud Abas|Part 3: Behavioral Design Patterns