行为模式 涉及 对象如何交互和通信 — 责任的分配和对象之间的通信流。它们包括 Observer、Strategy、Command、Iterator、State、Template Method 等。
行为模式解决的问题
BEHAVIORAL patterns concern how objects INTERACT, communicate, and distribute
responsibilities:
→ how objects collaborate and assign responsibilities to achieve behavior
→ manage algorithms, communication, and control flow between objects
→ about BEHAVIOR and interaction, not creation or structure
主要的行为模式
OBSERVER → notify many objects of state changes (covered separately) — very common
STRATEGY → interchangeable algorithms, swappable at runtime (covered separately) — common
COMMAND → encapsulate a request as an object (queue, log, undo operations)
ITERATOR → traverse a collection without exposing its internal structure
STATE → change behavior based on internal state (an object behaving like different "states")
TEMPLATE METHOD → define an algorithm's skeleton, let subclasses fill in steps
CHAIN OF RESPONSIBILITY → pass a request along a chain of handlers until one handles it
MEDIATOR → centralize complex communication between objects (reduce direct coupling)
