Skip to content

Commit e4a74bd

Browse files
authored
Merge pull request eugenp#6143 from dionisPrifti/BAEL-2441-Java-Enums-for_State-Machines
BAEL-2441: Providing example for State Machines with Enums
2 parents c7a8627 + e7c5d7a commit e4a74bd

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.baeldung.algorithms.enumstatemachine;
2+
3+
public enum LeaveRequestState {
4+
5+
Submitted {
6+
@Override
7+
public LeaveRequestState nextState() {
8+
System.out.println("Starting the Leave Request and sending to Team Leader for approval.");
9+
return Escalated;
10+
}
11+
12+
@Override
13+
public String responsiblePerson() {
14+
return "Employee";
15+
}
16+
},
17+
Escalated {
18+
@Override
19+
public LeaveRequestState nextState() {
20+
System.out.println("Reviewing the Leave Request and escalating to Department Manager.");
21+
return Approved;
22+
}
23+
24+
@Override
25+
public String responsiblePerson() {
26+
return "Team Leader";
27+
}
28+
},
29+
Approved {
30+
@Override
31+
public LeaveRequestState nextState() {
32+
System.out.println("Approving the Leave Request.");
33+
return this;
34+
}
35+
36+
@Override
37+
public String responsiblePerson() {
38+
return "Department Manager";
39+
}
40+
};
41+
42+
public abstract String responsiblePerson();
43+
44+
public abstract LeaveRequestState nextState();
45+
46+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.baeldung.algorithms.enumstatemachine;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import org.junit.Test;
6+
7+
public class LeaveRequestStateUnitTest {
8+
9+
@Test
10+
public void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
11+
LeaveRequestState state = LeaveRequestState.Escalated;
12+
13+
assertEquals(state.responsiblePerson(), "Team Leader");
14+
}
15+
16+
17+
@Test
18+
public void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
19+
LeaveRequestState state = LeaveRequestState.Approved;
20+
21+
assertEquals(state.responsiblePerson(), "Department Manager");
22+
}
23+
24+
@Test
25+
public void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
26+
LeaveRequestState state = LeaveRequestState.Submitted;
27+
28+
state = state.nextState();
29+
assertEquals(state, LeaveRequestState.Escalated);
30+
31+
state = state.nextState();
32+
assertEquals(state, LeaveRequestState.Approved);
33+
34+
state = state.nextState();
35+
assertEquals(state, LeaveRequestState.Approved);
36+
}
37+
}

0 commit comments

Comments
 (0)