-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStateTest.java
More file actions
121 lines (94 loc) · 2.27 KB
/
StateTest.java
File metadata and controls
121 lines (94 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
A Behavioral Pattern.
The State pattern is useful when you want to have an object represent
the state of an application, and you want to change the state by changing
that object. The State pattern is intended to provide a mechanism to allow
an object to alter its behavior in response to internal state changes.
To the client, it appears as though the object has changed its class.
The benefit of the State pattern is that state-specific logic is localized
in classes that represent that state.
*/
public class StateTest {
public static void main(String[] args){
System.out.println("-------------- STATE ---------------");
H2O h2o = new H2O(20.0, new Water());
System.out.println("Got some: "+h2o.getState().getClass().getName()+" at "+h2o.getTemp());
h2o.raiseTemp(120.0);
System.out.println("Got some: "+h2o.getState().getClass().getName()+" at "+h2o.getTemp());
h2o.lowerTemp(150.0);
System.out.println("Got some: "+h2o.getState().getClass().getName()+" at "+h2o.getTemp());
}
}
// Context
class H2O {
double temp;
State currentState;
H2O(double t, State st){
temp = t;
currentState = st;
}
public double getTemp(){
return temp;
}
public State getState(){
return currentState;
}
public void raiseTemp(double t){
temp = temp+t;
currentState = currentState.setTemp(temp);
}
public void lowerTemp(double t){
temp = temp-t;
currentState = currentState.setTemp(temp);
}
};
// State
abstract class State {
double uTemp;
double lTemp;
public abstract State setTemp(double t);
};
// State 1
class Ice extends State {
Ice(){
uTemp = 0.0;
lTemp = -100;
}
public State setTemp(double t){
if(t > uTemp){
State st = new Water();
return st.setTemp(t);
}
return this;
}
};
// State 2
class Water extends State {
Water(){
uTemp = 100.0;
lTemp = 0.0;
}
public State setTemp(double t){
if(t > uTemp){
return new Vapour();
}
if(t < lTemp){
return new Ice();
}
return this;
}
};
// State 3
class Vapour extends State {
Vapour(){
uTemp = 1000;
lTemp = 100;
}
public State setTemp(double t){
if(t < lTemp){
State st = new Water();
return st.setTemp(t);
}
return this;
}
};