Skip to content

Commit 67c209b

Browse files
authored
状态模式
状态模式
1 parent c97cdca commit 67c209b

File tree

5 files changed

+89
-0
lines changed

5 files changed

+89
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.java.design.state;
2+
3+
/**
4+
* 定义状态
5+
*
6+
* @author Administrator
7+
*
8+
*/
9+
public class Context {
10+
11+
private State state;
12+
13+
public State getState() {
14+
return state;
15+
}
16+
17+
public void setState(State state) {
18+
this.state = state;
19+
}
20+
21+
public String stateMessage() {
22+
return state.getState();
23+
}
24+
25+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.java.design.state;
2+
3+
public class Rain implements State {
4+
5+
@Override
6+
public String getState() {
7+
8+
return "Rain";
9+
}
10+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.java.design.state;
2+
3+
/**
4+
* 状态接口
5+
*
6+
* @author Administrator
7+
*
8+
*/
9+
public interface State {
10+
11+
/**
12+
* 获取状态
13+
*
14+
* @return
15+
*/
16+
String getState();
17+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.java.design.state;
2+
3+
/**
4+
* 状态模式 ----->
5+
* 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。允许一个对象在其内部状态改变时改变它的行为
6+
* 对象看起来似乎修改了它的类
7+
*
8+
* @author Administrator
9+
*
10+
*/
11+
public class StatePattern {
12+
13+
public static void main(String[] args) {
14+
15+
Context context = new Context();
16+
context.setState(new SunShine());
17+
String messageSun = context.stateMessage();
18+
System.out.println(messageSun);
19+
20+
System.out.println("----------------");
21+
22+
context.setState(new Rain());
23+
String messageRain = context.stateMessage();
24+
System.out.println(messageRain);
25+
}
26+
27+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.java.design.state;
2+
3+
public class SunShine implements State {
4+
5+
@Override
6+
public String getState() {
7+
8+
return "SunShine";
9+
}
10+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy