英文原文:http://www.dofactory.com/Patterns/PatternState.aspx
一、State Pattern (状态模式)
Define: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
定义:当一个对象的内部状态进行改变的时候允许对象改变其行为。这个对象将显然可以改变其类。
二、UML类图
- Context (Account)
- defines the interface of interest to clients
- maintains an instance of a ConcreteState subclass that defines the current state.
- State (State)
- defines an interface for encapsulating the behavior associated with a particular state of the Context.
- Concrete State (RedState, SilverState, GoldState)
- each subclass implements a behavior associated with a state of Context
三、State Pattern (状态模式)实例性代码
四、使用State Pattern (状态模式)的实例代码
This real-world code demonstrates the State pattern which allows an Account to behave differently depending on its balance. The difference in behavior is delegated to State objects called RedState, SilverState and GoldState. These states represent overdrawn accounts, starter accounts, and accounts in good standing.