All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.yangziwen.quickstate.impl.StateImpl Maven / Gradle / Ivy

There is a newer version: 0.0.5
Show newest version
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());
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy