状态模式

状态模式要达到的目的:允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类

具体实例


Application
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package zhuangtaimoshi;

/**
* Created by 15581 on 2017/11/8.
*/ // Application.java
public class Application{
public static void main(String args[]) {
TemperatureState state=new LowState(-12);
Thermometer thermometer=new Thermometer();
thermometer.setState(state);
thermometer.showMessage();
state=new MiddleState(20);
thermometer.setState(state);
thermometer.showMessage();
state=new HeightState(39);
thermometer.setState(state);
thermometer.showMessage();
}
}

HeightState

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package 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+"属于高温度");
}
}

LowState

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package 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+"属于低温度");
}
}

MiddleState

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package 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+"属于正常温度");
}
}

TemperatureState

1
2
3
4
5
6
7
8
package zhuangtaimoshi;

/**
* Created by 15581 on 2017/11/8.
*/ // TemperatureState.java
public interface TemperatureState{
public void showTemperature();
}

Thermometer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package 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;
}
}