Design Patterns — Fast Recall (Python)
State — behavior changes with internal state
- What: an object delegates behavior to a state object; changing state changes behavior — a clean state machine.
- Why / when: an entity moves through statuses with different rules — order (placed→shipped→delivered), TCP connection, media player.
- Kills: sprawling `if status == ...` checks scattered everywhere; each state owns its own transitions.
- vs Strategy: structurally similar, but State transitions itself between states; Strategy is chosen from outside.
1class Draft:
2 def publish(self, post): post.state = Published()
3class Published:
4 def publish(self, post): print("already live")
5
6class Post:
7 def __init__(self): self.state = Draft()
8 def publish(self): self.state.publish(self)
9
10p = Post(); p.publish() # Draft -> Published
11p.publish() # already live