状态模式常用于运行时变更状态。
状态模式故事
人可能生活在不同的经济状态下,可能富有,可能贫穷。随着时间的迁移,富有与贫穷两个状态可以相互转换,这个想法背后的例子:当他们贫穷时通常辛苦工作,当他们富有时玩得更多。他们所做的是根据他们生活环境,通过他们的行为,这个状态可以改变,否则这个社会就不会长久。
状态模式类图
这里是类图,你可以比较 策略模式,得到两者之间的差别。
状态模式Java代码
下面java代码展示了状态模式如果工作。 State classes:
package com.programcreek.designpatterns.state;
interface State {
public void saySomething(StateContext sc);
}
class Rich implements State{
@Override
public void saySomething(StateContext sc) {
System.out.println("I'm rick currently, and play a lot.");
sc.changeState(new Poor());
}
}
class Poor implements State{
@Override
public void saySomething(StateContext sc) {
System.out.println("I'm poor currently, and spend much time working.");
sc.changeState(new Rich());
}
}
StateContext class:
package com.programcreek.designpatterns.state;
public class StateContext {
private State currentState;
public StateContext(){
currentState = new Poor();
}
public void changeState(State newState){
this.currentState = newState;
}
public void saySomething(){
this.currentState.saySomething(this);
}
}
Main class for testing:
import com.programcreek.designpatterns.*;
public class Main {
public static void main(String args[]){
StateContext sc = new StateContext();
sc.saySomething();
sc.saySomething();
sc.saySomething();
sc.saySomething();
}
}
Result:
I'm poor currently, and spend much time working.
I'm rick currently, and play a lot.
I'm poor currently, and spend much time working.
I'm rick currently, and play a lot.