状态模式要达到的目的:允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类
具体实例
Application
1 | package zhuangtaimoshi; |
HeightState1
2
3
4
5
6
7
8
9
10
11
12
13
14
15package zhuangtaimoshi;
/**
* Created by 15581 on 2017/11/8.
*/ // HeightState.java
public class HeightState implements TemperatureState{
double n=26;
HeightState(int n){
if(n>26)
this.n=n;
}
public void showTemperature(){
System.out.println("现在温度是"+n+"属于高温度");
}
}
LowState1
2
3
4
5
6
7
8
9
10
11
12
13
14
15package zhuangtaimoshi;
/**
* Created by 15581 on 2017/11/8.
*/ // LowState.java
public class LowState implements TemperatureState{
double n=0;
LowState(double n){
if(n<=0)
this.n=n;
}
public void showTemperature(){
System.out.println("现在温度是"+n+"属于低温度");
}
}
MiddleState1
2
3
4
5
6
7
8
9
10
11
12
13
14
15package zhuangtaimoshi;
/**
* Created by 15581 on 2017/11/8.
*/ // MiddleState.java
public class MiddleState implements TemperatureState{
double n=10;
MiddleState(int n){
if(n>0&&n<=26)
this.n=n;
}
public void showTemperature(){
System.out.println("现在温度是"+n+"属于正常温度");
}
}
TemperatureState1
2
3
4
5
6
7
8package zhuangtaimoshi;
/**
* Created by 15581 on 2017/11/8.
*/ // TemperatureState.java
public interface TemperatureState{
public void showTemperature();
}
Thermometer1
2
3
4
5
6
7
8
9
10
11
12
13
14package zhuangtaimoshi;
// Thermometer.java
public class Thermometer{
TemperatureState state;
public void showMessage(){
System.out.println("***********");
state.showTemperature();
System.out.println("***********");
}
public void setState(TemperatureState state){
this.state=state;
}
}