Preface: [ Mode Overview ] ---------- by xingoo
Intention mode
It allows an object to change its internal state, and has a different behavior depending on the operation state.
For example, the water in the solid, liquid, gas is three states, but in front of us really different feeling. By changing the state of the water, you can change it to show the way.
Scenarios
1 when the behavior of an object, depending on its state
When there are two branches of a large number of class structure, and an operation within each abstract same branch, as may be performed when a condition.
Mode structure
Context environmental role, which contains the state object
class Context{
private State state;
public void setState(State state) {
this.state = state;
}
public void operation(){
state.operation();
}
}
State state of the abstract interface
interface State{
public void operation();
}
ConcreteState specific role of the state
class ConcreteState1 implements State{
public void operation(){
System.out.println("state1 operation");
}
}
class ConcreteState2 implements State{
public void operation(){
System.out.println("state2 operation");
}
}
class ConcreteState3 implements State{
public void operation(){
System.out.println("state3 operation");
}
}
All codes
1 package com.xingoo.test.design.state;
2 class Context{
3 private State state;
4 public void setState(State state) {
5 this.state = state;
6 }
7 public void operation(){
8 state.operation();
9 }
10 }
11 interface State{
12 public void operation();
13 }
14 class ConcreteState1 implements State{
15 public void operation(){
16 System.out.println("state1 operation");
17 }
18 }
19 class ConcreteState2 implements State{
20 public void operation(){
21 System.out.println("state2 operation");
22 }
23 }
24 class ConcreteState3 implements State{
25 public void operation(){
26 System.out.println("state3 operation");
27 }
28 }
29 public class Client {
30 public static void main(String[] args) {
31 Context ctx = new Context();
32 State state1 = new ConcreteState1();
33 State state2 = new ConcreteState2();
34 State state3 = new ConcreteState3();
35
36 ctx.setState(state1);
37 ctx.operation();
38
39 ctx.setState(state2);
40 ctx.operation();
41
42 ctx.setState(state3);
43 ctx.operation();
44 }
45 }
operation result
state1 operation
state2 operation
state3 operation
Reproduced in: https: //my.oschina.net/u/204616/blog/545493