Adapting with Every Change
In essence, the State Design Pattern allows your code to be like a chameleon, seamlessly blending in with the ever-changing conditions, adapting its behavior with each shift in its internal state. This promotes clarity, maintainability, and flexibility, making your program a master of adaptability.
from abc import ABC, abstractmethod
class DocumentState(ABC):
@abstractmethod
def key_pressed(self, key):
pass
@abstractmethod
def save_request(self):
pass
class EditingState(DocumentState):
def key_pressed(self, key):
print("Typing character:", key)
def save_request(self):
print("Saving document...")
class FormattingState(DocumentState):
def key_pressed(self, key):
print("Applying formatting:", key)
def save_request(self):
print("Formatting not allowed in this state.")
class DocumentContext:
def __init__(self):
self.state = EditingState() # Default state
def handle_event(self, event):
self.state.handle_event(event)
# Client code using the State pattern
context = DocumentContext()
context.handle_event("key_pressed", "a") # Output: Typing character: a
context.handle_event("save_request") # Output: Saving document...
context.state = FormattingState()
context.handle_event("key_pressed", "b") # Output: Applying formatting: b
context.handle_event("save_request") # Output: Formatting not allowed in this state.