Merge pull request #6143 from dionisPrifti/BAEL-2441-Java-Enums-for_State-Machines
BAEL-2441: Providing example for State Machines with Enums
This commit is contained in:
commit
e4a74bd6f6
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.algorithms.enumstatemachine;
|
||||
|
||||
public enum LeaveRequestState {
|
||||
|
||||
Submitted {
|
||||
@Override
|
||||
public LeaveRequestState nextState() {
|
||||
System.out.println("Starting the Leave Request and sending to Team Leader for approval.");
|
||||
return Escalated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String responsiblePerson() {
|
||||
return "Employee";
|
||||
}
|
||||
},
|
||||
Escalated {
|
||||
@Override
|
||||
public LeaveRequestState nextState() {
|
||||
System.out.println("Reviewing the Leave Request and escalating to Department Manager.");
|
||||
return Approved;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String responsiblePerson() {
|
||||
return "Team Leader";
|
||||
}
|
||||
},
|
||||
Approved {
|
||||
@Override
|
||||
public LeaveRequestState nextState() {
|
||||
System.out.println("Approving the Leave Request.");
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String responsiblePerson() {
|
||||
return "Department Manager";
|
||||
}
|
||||
};
|
||||
|
||||
public abstract String responsiblePerson();
|
||||
|
||||
public abstract LeaveRequestState nextState();
|
||||
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.algorithms.enumstatemachine;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LeaveRequestStateUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
|
||||
LeaveRequestState state = LeaveRequestState.Escalated;
|
||||
|
||||
assertEquals(state.responsiblePerson(), "Team Leader");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
|
||||
LeaveRequestState state = LeaveRequestState.Approved;
|
||||
|
||||
assertEquals(state.responsiblePerson(), "Department Manager");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
|
||||
LeaveRequestState state = LeaveRequestState.Submitted;
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Escalated);
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Approved);
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Approved);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue