vendredi 1 février 2019

Best practices to model the change of states of an object in time?

I'm currently working on a java webapp, and I have trouble trying to model the change of states of an object that depends on a start/end date.

As i need to change states in runtime, I'm following the State Pattern for the states, but I have doubts about the proper way to check for the conditions to change states. For example, I have a simple Event class, with an abstract EventState that is empty:

public class Event {
    private Long Id;
    private String title;
    private LocalDate startDate;     //mm/dd/yyyy
    private LocalTime startTime;     //hour:minutes
    private LocalDate endDate;       //mm/dd/yyyy
    private LocalTime endTime;       //hour:minutes
    private EventState eventState;
    ...

    //getters, setters, validation,etc

}

And also, many states, some of which depends on the start/endDate. Like starting an event automatically in the startDate, and finishing it in the endDate:

public class StatedState extends EventState {
     //my methods that works for a started Event
}

public class FinishedState extends EventState {
     //my methods that works for a finished Event
}

My current approach is a Scheduler class that checks every Event a minute, and updates the states that way.

Considering that I will have many instances of Event in my application, is there any recomendation or approach to checking for time-based conditions when using the state pattern? Or should I not be using the state pattern for those states in particular?

Aucun commentaire:

Enregistrer un commentaire