Skip to content

Commit 4c9ea99

Browse files
author
PRIFTI
committed
BAEL-2441: Providing example for Implementing simple State Machine with Java Enums.
1 parent f1fa9c8 commit 4c9ea99

2 files changed

Lines changed: 87 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
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+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.algorithms.enumstatemachine;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import org.junit.Test;
6+
7+
public class LeaveRequestStateTest {
8+
9+
@Test
10+
public void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
11+
LeaveRequestState state = LeaveRequestState.Escalated;
12+
13+
String responsible = state.responsiblePerson();
14+
15+
assertEquals(responsible, "Team Leader");
16+
}
17+
18+
19+
@Test
20+
public void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
21+
LeaveRequestState state = LeaveRequestState.Approved;
22+
23+
String responsible = state.responsiblePerson();
24+
25+
assertEquals(responsible, "Department Manager");
26+
}
27+
28+
@Test
29+
public void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
30+
LeaveRequestState state = LeaveRequestState.Submitted;
31+
32+
state = state.nextState();
33+
assertEquals(state, LeaveRequestState.Escalated);
34+
35+
state = state.nextState();
36+
assertEquals(state, LeaveRequestState.Approved);
37+
38+
state = state.nextState();
39+
assertEquals(state, LeaveRequestState.Approved);
40+
}
41+
}

0 commit comments

Comments
 (0)