Status Mode: allows the object to change its behavior in the internal state of change, the object appears to modify its class.
State interfaces (abstract classes) defines a particular state of generating all the common interface, then the interface state class implement can be interchangeable.
Context class has a state number, () method of the request through the request of a state of the object's behavior
ConcreteStateA state is a specific implementation of the interface class to provide specific implementation of the present state of processing requests from a Context Context behavior changes such changes state.
定义一个State接口,包含了所有状态的方法(抽象类可以减少代码重复)
public interface State{
insertQuarter();
dispense();
}
封装变化,状态类实现接口,修改封闭,将每个状态的行为放到各自的类中(行为局部化)
实现符合这个状态的行为,某些情况下改变Context状态从而使得Context使用另一个状态实例的方法
public class NoQuarterState implements State{
GunballMachine gunMa;
public NoQuarterState(GUnballMachine gunMa){
this.gunMa=gunMa;
}
public void insertQuarter(){
//System..
gunMa.setState(gunMa.getHasQuarterState()); //让Context状态改变
}
//其它方法
}
多用组合,Context委托状态给相应的状态对象,
包含所有的状态实例,某刻只有一个状态
可以加入其他状态类对扩展开放
public class GumballMachine{
State noQuarterState;
//State ..
State state=noQuarterState; //初始状态
int count=0; //一些状态改变的判断条件
public GumballMachine(int numberGumballs){ //通过初始数量来决定状态
noQrarterState=new NoQuarter(this); //为每种状态类创建实例
//
this.count=numberGumballs;
if(count>0){
state=
}
}
public void insertQuarter(){
state.insertQuarter(); //动作不自己实现,委托到了相应状态对象中
}
//其他类似行为
public void turnGrank(){ //Context的内部动作,通过状态对象进行调用
state.dispense();
}
void setState(State state){ //允许状态对象转换状态
this.state=state;
}
//其他方法,比如改变判断条件,set,get
}
Summary: This mode status packaged into separate categories, the operation will be entrusted to the object representing the current state of the different states of the object referenced by a simple behavioral changes with the internal state. Compared with the strategy pattern, specify a combination of policy initiative to change the behavior of objects, like changing behavior but without the use of state of the object-dependent conditional.