if (which==1) state="hello"; else if (which==2) state="hi"; else if (which==3) state="bye";
if (state.euqals("bye")) state="hello"; else if (state.euqals("hello")) state="hi"; else if (state.euqals("hi")) state="bye";
public class Context{ private Color state=null; public void push(){ //如果当前red状态,切换到blue if (state==Color.red) state=Color.blue; //如果当前blue状态,切换到green else if (state==Color.blue) state=Color.green; //如果当前black状态,切换到red else if (state==Color.black) state=Color.red; //如果当前green状态,切换到black else if (state==Color.green) state=Color.black; Sample sample=new Sample(state); sample.operate(); } public void pull(){ //与push状态切换正好相反 if (state==Color.green) state=Color.blue; else if (state==Color.black) state=Color.green; else if (state==Color.blue) state=Color.red; else if (state==Color.red) state=Color.black; Sample2 sample2=new Sample2(state); sample2.operate(); } }
public abstract class State{ public abstract void handlepush(Context c); public abstract void handlepull(Context c); public abstract void getcolor(); }
public class BlueState extends State{ public void handlepush(Context c){ System.out.println(“变成绿色"); c.setState(new GreenState()); } public void handlepull(Context c){ System.out.println(“变成红色"); c.setState(new RedState()); } public abstract void getcolor(){ return (Color.blue); } }
public class GreenState extends State{ public void handlepush(Context c){ System.out.println(“变成黑色"); c.setState(new BlackState()); } public void handlepull(Context c){ System.out.println(“变成蓝色"); c.setState(new BlueState()); } public abstract void getcolor(){ return (Color.green); } }
public class BlackState extends State{ public void handlepush(Context c){ System.out.println(“变成红色"); c.setState(new RedState()); } public void handlepull(Context c){ System.out.println(“变成红色"); c.setState(new RedState()); } public abstract void getcolor(){ return (Color.black); } }
public class RedState extends State{ public void handlepush(Context c){ System.out.println(“变成蓝色"); c.setState(new BlueState()); } public void handlepull(Context c){ System.out.println(“变成黑色"); c.setState(new BlackState()); } public abstract void getcolor(){ return (Color.red); } }
public class Context{ private Sate state=null; //我们将原来的 Color state 改成了新建的State state; //setState是用来改变state的状态 使用setState实现状态的切换 pulic void setState(State state){ this.state=state; } public void push(){ //状态的切换的细节部分,在本例中是颜色的变化,已经封装在子类的handlepush中实现,这里无需关心 state.handlepush(this); //假设sample要使用state中的一个切换结果,使用getColor() Sample sample=new Sample(state.getColor()); sample.operate(); } public void pull(){ state.handlepull(this); //假设sample要使用state中的一个切换结果,使用getColor() Sample2 sample2=new Sample2(state.getColor()); sample2.operate(); } }
原文地址:http://blog.csdn.net/jason0539/article/details/45021055