Last active
November 8, 2016 18:04
-
-
Save msvab/35ec0a9bf0fce2ea499a6e5f47a3d8b0 to your computer and use it in GitHub Desktop.
event-lib refactor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public abstract class AbstractStateTransition<STATE, EVENT extends Event<?>> implements StateTransitionFunctions<STATE, EVENT> { | |
| public STATE applyTransition(final STATE currentState, final EVENT event) { | |
| Preconditions.checkArgument(currentState != null); | |
| Preconditions.checkArgument(event != null); | |
| validateStartingState(currentState, event); | |
| final STATE newState = updateState(currentState, event); | |
| notifyTransitionObservers(newState, event); | |
| return newState; | |
| } | |
| public abstract STATE updateState(STATE state, EVENT event); | |
| } | |
| public class NotificationRequestedTransition extends AbstractStateTransition<NotificationState, NotificationRequestedEvent> { | |
| public NotificationState updateState(NotificationState state, NotificationRequestedEvent event) { | |
| state.setRequestedDate(event.getTimestampt()); | |
| state.setStateType(NotificationStateType.NOTIFICATION_REQUESTED); | |
| } | |
| } | |
| public class NotificationSentTransition extends AbstractStateTransition<NotificationState, NotificationSentEvent> { | |
| public NotificationState updateState(NotificationState state, NotificationSentEvent event) { | |
| state.setSentDate(event.getTimestampt()); | |
| state.setStateType(NotificationStateType.NOTIFICATION_SENT); | |
| } | |
| } | |
| public class NotficationTransitions { | |
| public static final Map<Tuple<NotificationStateType, Class<NotificationEvent>>, AbstractEventTransition<NotificationEvent>> TRANSITIONS | |
| = ImmutableMap.of(tuple(NOTIFICATION_INITIATED, NotificationRequestedEvent.class), new NotificationRequestedTransition(), | |
| tuple(NOTIFICATION_REQUESTED, NotificationSentEvent.class), new NotificationSentTransition()); | |
| } | |
| public class NotificationStateMachine implements StateMachine<NotificationState, NotificationEvent> { | |
| @Override | |
| public NotificationState getCurrentStateFromStream(final EventStream<NotificationEvent> eventStream) { | |
| return eventStream.getEvents().stream().reduce( | |
| NOTIFICATION_OPERATION_INITIATED, | |
| (NotificationState s, NotificationEvent e) -> this.applyTransition(s, e) | |
| , (state1, state2) -> state2); | |
| } | |
| @Override | |
| public NotificationState applyTransition(final NotificationState currentState, | |
| final NotificationEvent event) { | |
| return NotficationTransitions.TRANSITIONS.get(tuple(currentState.getStateType(), event.getClass())).applyTransition(currentState, event)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment