# 《Java极简设计模式》第20章:状态模式(State)
作者:冰河
星球:http://m6z.cn/6aeFbs (opens new window)
博客:https://binghe.gitcode.host (opens new window)
文章汇总:https://binghe.gitcode.host/md/all/all.html (opens new window)
源码地址:https://github.com/binghe001/java-simple-design-patterns/tree/master/java-simple-design-state (opens new window)
沉淀,成长,突破,帮助他人,成就自我。
- 本章难度:★★☆☆☆
- 本章重点:用最简短的篇幅介绍状态模式最核心的知识,理解状态模式的设计精髓,并能够灵活运用到实际项目中,编写可维护的代码。
大家好,我是CurleyG~~
今天给大家介绍《Java极简设计模式》的第20章:状态模式(State),多一句没有,少一句不行,用最简短的篇幅讲述设计模式最核心的知识,好了,开始今天的内容。
# 一、概述
定义对象行为状态,并且能够在运行时刻根据状态改变行为。
# 二、适用性
1.一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为。
2.一个操作中含有庞大的多分支条件语句,且这些分支依赖于该对象的状态。 这个状态通常用一个或多个枚举常量表示。 通常,有多个操作包含这一相同的条件结构。 State模式将每一个条件分支放入一个独立的类中。 这样就可以根据对象自身的情况将对象的状态作为一个对象,这一对象可以不依赖于其他对象而独立变化。
# 三、适用性
1.Context 定义接口。 维护一个ConcreteState子类的实例,这个实例定义当前状态。
2.State 定义一个接口用来封装与Context的一个特定状态相关的行为。
3.ConcreteStatesubclasses 每一个子类实现一个与Context的一个状态相关的行为。
# 四、类图
# 五、示例
Context
/**
* @author binghe(微信 : hacker_binghe)
* @version 1.0.0
* @description Context
* @github https://github.com/binghe001
* @copyright 公众号: 冰河技术
*/
public class Context {
private Weather weather;
public void setWeather(Weather weather) {
this.weather = weather;
}
public Weather getWeather() {
return this.weather;
}
public String weatherMessage() {
return weather.getWeather();
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
State
/**
* @author binghe(微信 : hacker_binghe)
* @version 1.0.0
* @description State
* @github https://github.com/binghe001
* @copyright 公众号: 冰河技术
*/
public interface Weather {
String getWeather();
}
2
3
4
5
6
7
8
9
10
ConcreteStatesubclasses
/**
* @author binghe(微信 : hacker_binghe)
* @version 1.0.0
* @description ConcreteStatesubclasses
* @github https://github.com/binghe001
* @copyright 公众号: 冰河技术
*/
public class Rain implements Weather {
@Override
public String getWeather() {
return "下雨";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @author binghe(微信 : hacker_binghe)
* @version 1.0.0
* @description ConcreteStatesubclasses
* @github https://github.com/binghe001
* @copyright 公众号: 冰河技术
*/
public class Sunshine implements Weather{
@Override
public String getWeather() {
return "阳光";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
Test
/**
* @author binghe(微信 : hacker_binghe)
* @version 1.0.0
* @description 测试类
* @github https://github.com/binghe001
* @copyright 公众号: 冰河技术
*/
public class Test {
public static void main(String[] args) {
Context ctx1 = new Context();
ctx1.setWeather(new Sunshine());
System.out.println(ctx1.weatherMessage());
System.out.println("===============");
Context ctx2 = new Context();
ctx2.setWeather(new Rain());
System.out.println(ctx2.weatherMessage());
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Result
阳光
===============
下雨
2
3
好了,今天就到这儿吧,相信大家对状态模式有了更清晰的了解,我是冰河,我们下期见~~
← 第19章:观察者模式 第21章:策略模式 →
