下图是关于红绿灯转换的一个实现类图,具体的转换是这样子的,在初始的情况下,设定一个灯的状态,比如是绿灯,那么灯的下一个状态则是黄灯,紧接着是红灯,然后再是绿灯,依次循环;通过改变灯的状态,改变其行为。
package com.plabmedia.state;
public interface LightState {
/**
* 打印当前的状态
*/
public void print(Light light);
}
package com.plabmedia.state;
public class RedLight implements LightState{
@Override
public void print(Light light) {
System.out.println("current state is red");
light.setState(new GreenLight());
}
}
package com.plabmedia.state;
public class YellowLight implements LightState{
@Override
public void print(Light light) {
System.out.println("current state is yellow");
light.setState(new RedLight());
}
}
package com.plabmedia.state;
public class GreenLight implements LightState {
@Override
public void print(Light light) {
System.out.println("current state is green");
light.setState(new YellowLight());
}
}
package com.plabmedia.state;
public class Light {
private LightState state;
public LightState getState() {
return state;
}
public void setState(LightState state) {
this.state = state;
}
public void print(){
state.print(this);
}
public Light(LightState state){
this.state = state;
}
}
package com.plabmedia.state;
public class Client {
public static void main(String args[]){
Light light = new Light(new GreenLight());
light.print();
light.print();
light.print();
light.print();
light.print();
light.print();
}
}
上面是对状态模式一个小小的实现,这个实现也仅仅是认识级的,在我们实际应用中,如果用到状态模式,应该比这个要负责的多,只是基本的结构是相似的。那我们下面针对状态模式做一些讨论。