基本概念
State Pattern: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
相关联系
- 状态模式可被视为 策略模式 的扩展。 两者都基于组合机制,它们都通过将部分工作委派给 “帮手” 对象来改变其在不同情景下的行为。
- 策略使得这些对象相互之间完全独立, 它们不知道其他对象的存在。
- 状态模式没有限制具体状态之间的依赖, 且允许它们自行改变在不同情景下的状态。
实现代码
上下文
状态
测试类
Q & A
You could use simple subclassing instead of this kind of design. Is this correct?
No. With simple subclassing, your implementations cannot vary dynamically. It may appear that the implementations behave differently with subclassing techniques, but actually, those kinds of variations are already bound to the abstraction at compile time
What are the common characteristics between the strategy pattern and the state pattern?
Both can promote composition and delegation.