io.github.yangziwen.quickstate.impl.StateImpl Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of quick-state Show documentation
Show all versions of quick-state Show documentation
A lightweight state machine
package io.github.yangziwen.quickstate.impl;
import java.util.ArrayList;
import java.util.List;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import io.github.yangziwen.quickstate.State;
import io.github.yangziwen.quickstate.Transition;
import io.github.yangziwen.quickstate.TransitionType;
import io.github.yangziwen.quickstate.Visitor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class StateImpl implements State {
@EqualsAndHashCode.Include
private final S id;
private List> groups = new ArrayList<>();
private ListMultimap> transitions = ArrayListMultimap.create();
StateImpl(S id) {
this.id = id;
}
@Override
public S getId() {
return id;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@Override
public Transition addTransition(E event, State target, TransitionType type) {
TransitionImpl transition = TransitionImpl.builder()
.source(this)
.target(target)
.event(event)
.build();
verify(event, transition);
transitions.put(event, transition);
return transition;
}
public StateImpl addStateGroup(StateGroup group) {
if (group != null) {
this.groups.add(group);
}
return this;
}
@Override
public List> getStateGroups() {
return this.groups;
}
@Override
public List> getTransitions(E event) {
return transitions.get(event);
}
@Override
public List> getAllTransitions() {
return new ArrayList<>(transitions.values());
}
private void verify(E event, Transition transition) {
if(transitions.values().contains(transition)){
throw new StateMachineException(transition + " already Exist, you can not add another one");
}
}
@Override
public String toString() {
return String.valueOf(getId());
}
}