Skip to content

Commit d7c37a1

Browse files
author
Liu Yuning
committed
add state DP
1 parent 5603a7b commit d7c37a1

File tree

3 files changed

+91
-0
lines changed

3 files changed

+91
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package designpattern.state;
2+
3+
/**
4+
* Context类,维护一个ConcreteState子类的实例,这个实例定义当前的状态
5+
*
6+
* @author liu yuning
7+
*
8+
*/
9+
public class Context {
10+
private State state;
11+
12+
public Context(State state) {
13+
this.state = state;
14+
}
15+
16+
public State getState() {
17+
return state;
18+
}
19+
20+
public void setState(State state) {
21+
this.state = state;
22+
}
23+
24+
public void request() {
25+
this.state.handle(this);
26+
}
27+
}

src/designpattern/state/State.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package designpattern.state;
2+
3+
/**
4+
* 抽象状态类
5+
*
6+
* @author liu yuning
7+
*
8+
*/
9+
public abstract class State {
10+
public abstract void handle(Context context);
11+
12+
}
13+
14+
class ConcreteStateA extends State {
15+
16+
@Override
17+
public void handle(Context context) {
18+
System.out.println("现在是在状态A");
19+
context.setState(new ConcreteStateB());
20+
}
21+
22+
}
23+
24+
class ConcreteStateB extends State {
25+
26+
@Override
27+
public void handle(Context context) {
28+
System.out.println("现在是在状态B");
29+
context.setState(new ConcreteStateC());
30+
31+
}
32+
33+
}
34+
35+
class ConcreteStateC extends State {
36+
37+
@Override
38+
public void handle(Context context) {
39+
System.out.println("现在是在状态C");
40+
context.setState(new ConcreteStateA());
41+
42+
}
43+
44+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package designpattern.state;
2+
3+
/**
4+
* 客户端:不断请求,不断更改状态
5+
*
6+
* @author liu yuning
7+
*
8+
*/
9+
public class StateClient {
10+
public static void main(String[] args) {
11+
12+
Context context = new Context(new ConcreteStateA());
13+
14+
context.request();
15+
context.request();
16+
context.request();
17+
context.request();
18+
context.request();
19+
}
20+
}

0 commit comments

Comments
 (0)