forked from hacker85/JavaLessons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDemoOfClientState.java
More file actions
59 lines (52 loc) · 1.59 KB
/
Copy pathDemoOfClientState.java
File metadata and controls
59 lines (52 loc) · 1.59 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
package patterns;
public class DemoOfClientState {
public static void main(String[] args) {
final StateContext sc = new StateContext();
sc.writeName("Monday");
sc.writeName("Tuesday");
sc.writeName("Wednesday");
sc.writeName("Thursday");
sc.writeName("Friday");
sc.writeName("Saturday");
sc.writeName("Sunday");
}
}
interface Statelike {
void writeName(StateContext context, String name);
}
class StateLowerCase implements Statelike {
@Override
public void writeName(final StateContext context, final String name) {
System.out.println(name.toLowerCase());
context.setState(new StateMultipleUpperCase());
}
}
class StateMultipleUpperCase implements Statelike {
/** Counter local to this state */
private int count = 0;
@Override
public void writeName(final StateContext context, final String name) {
System.out.println(name.toUpperCase());
/* Change state after StateMultipleUpperCase's writeName() gets invoked twice */
if(++count > 1) {
context.setState(new StateLowerCase());
}
}
}
class StateContext {
private Statelike myState;
StateContext() {
setState(new StateLowerCase());
}
/**
* Setter method for the state.
* Normally only called by classes implementing the State interface.
* @param newState the new state of this context
*/
void setState(final Statelike newState) {
myState = newState;
}
public void writeName(final String name) {
myState.writeName(this, name);
}
}