System.out.println("I'm rick currently, and play a lot.");
sc.changeState(new Poor());
}
}
classPoorimplementsState{
@Override
publicvoidsaySomething(StateContext sc){
System.out.println("I'm poor currently, and spend much time working.");
sc.changeState(new Rich());
}
}
StateContext 类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.programcreek.designpatterns.state;
publicclassStateContext{
private State currentState;
publicStateContext(){
currentState = new Poor();
}
publicvoidchangeState(State newState){
this.currentState = newState;
}
publicvoidsaySomething(){
this.currentState.saySomething(this);
}
}
测试Main 类
1
2
3
4
5
6
7
8
9
10
11
import com.programcreek.designpatterns.*;
publicclassMain{
publicstaticvoidmain(String args[]){
StateContext sc = new StateContext();
sc.saySomething();
sc.saySomething();
sc.saySomething();
sc.saySomething();
}
}
结果:
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.