State
Intent
Allow an object to alter its behavior when its internal state changes.
How to
1.Context delegates state-specific requests to the current ConcreteState object.
2.Clients can configure a context with State objects. Once a context is configured, its clients don't have to deal with the State objects directly.
3.Either Context or the ConcreteState subclasses can decide which state succeeds another and under what circumstances.
Context
defines the interface of interest to clients.
maintains an instance of a ConcreteState subclass that defines the current state.
State
defines an interface for encapsulating the behavior associated with a particular state of the Context.
ConcreteState subclasses
each subclass implements a behavior associated with a state of the Context.
Known cases
Credit Account
Process
UML
假设账户有三种状态:
1.如果没透支,则取款不收取费用(NonfeeState)
2.如果透支数小于等于200,则取款费用为2元(FeeState)
3.如果透支数多于500,则不允许取款(OverdrawState)
代码:
说明:
(1)如果此例不运用状态模式,则会在Account中的withdraw和diposit方法中有if-else语句(如果发现一个类中有许多方法有相同的条件逻辑判断,可能表示这个类可以重构成状态模式)
(2)由于各个State子类无状态,因此全局只需使用一个实例即可