State Pattern
Bir objenin durumunu belirtmek için kullanılır. Objenin durumu runtime de sürekli değişiyorsa kullanılması uygun olur.
Örnek Java Implementasyonu:
State interface i ve iki implemantasyonu.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | interface State { public void writeName(StateContext stateContext, String name); } class StateA implements State { public void writeName(StateContext stateContext, String name) { System.out.println(name.toLowerCase()); stateContext.setState(new StateB()); } } class StateB implements State { private int count=0; public void writeName(StateContext stateContext, String name){ System.out.println(name.toUpperCase()); // change state after StateB's writeName() gets invoked twice if(++count>1) { stateContext.setState(new StateA()); } } } |
StateContext class i state objelerini tutar.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 public class StateContext {
private State myState;
public StateContext() {
setState(new StateA());
}
// normally only called by classes implementing the State interface
public void setState(State newState) {
this.myState = newState;
}
public void writeName(String name) {
this.myState.writeName(this, name);
}
}
Kullanımı
1 2 3 4 5 6 7 8 9 10 11 | public class TestClientState { public static void main(String[] args) { StateContext sc = new StateContext(); sc.writeName("Monday"); sc.writeName("Tuesday"); sc.writeName("Wednesday"); sc.writeName("Thursday"); sc.writeName("Saturday"); sc.writeName("Sunday"); } } |
Output
monday
TUESDAY
WEDNESDAY
thursday
SATURDAY
SUNDAY