Skip to content

Instantly share code, notes, and snippets.

@mok0
Created July 31, 2023 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mok0/510b229e6a0c3cb4061754e3c358b998 to your computer and use it in GitHub Desktop.
Save mok0/510b229e6a0c3cb4061754e3c358b998 to your computer and use it in GitHub Desktop.
# Example of state pattern by code EV
# https://youtu.be/8rynRTOr4mE
class State:
def receive_payment(self):
raise NotImplementedError()
def ship(self):
raise NotImplementedError()
def mark_delivered(self):
raise NotImplementedError()
class Order:
"""Context class 'state of states' """
def __init__(self) -> None:
self.unpaid_state = UnpaidState(self)
self.paid_state = PaidState(self)
self.shipped_state = ShippedState(self)
self.delivered_state = DeliveredState(self)
self.state = self.unpaid_state
def set_state(self, state: State):
self.state = state
def ship(self):
self.state.ship()
def receive_payment(self):
self.state.receive_payment()
def mark_delivered(self):
self.state.mark_delivered()
class UnpaidState(State):
def __init__(self, context: Order):
self.context = context
def __str__(self):
return __class__.__name__
def receive_payment(self):
self.context.set_state(self.context.paid_state)
print("Your payment was accepted")
def ship(self):
print("Can't ship unpaid orders")
def mark_delivered(self):
print("Can't deliver unpaid orders")
class PaidState(State):
def __init__(self, context: Order):
self.context = context
def __str__(self):
return __class__.__name__
def receive_payment(self):
print("Order has already been paid")
def ship(self):
self.context.set_state(self.context.shipped_state)
print("The order has been shipped")
def mark_delivered(self):
print("Only shipped orders can be marked delivered")
class ShippedState(State): ###
def __init__(self, context: Order):
self.context = context
def __str__(self):
return __class__.__name__
def receive_payment(self):
print("Order has already been paid")
def ship(self):
print("The order has been shipped")
def mark_delivered(self):
self.context.set_state(self.context.delivered_state)
print("Your order has been delivered")
class DeliveredState(State):
def __init__(self, context: Order):
self.context = context
def __str__(self):
return __class__.__name__
def receive_payment(self):
print("Order has already been paid")
def ship(self):
self.context.set_state(self.context.shipped_state)
print("The order has already been delivered, checkthe front door")
def mark_delivered(self):
print("The order has been delivered! Check the front door!")
if __name__ == "__main__":
order = Order()
print(order.state)
order.ship() # should generate error message
order.receive_payment()
print(order.state)
order.ship()
order.receive_payment() # should generate error message
print(order.state)
order.mark_delivered()
print(order.state)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment