I am using the State Pattern, but the examples I found are for educational purpose and I wanted to know what are best practices in this pattern for sharing objects between states, i.e. a boolean, a List and also for one state object to change the state reference in the automata object.
I will lay down a simple model to be used as an example.
public abstract class State {
Automata automata;
public State( Automata automata){
this.automata = automata;
}
public abstract void action();
}
public class State1 extends State {
public State1(Automata automata){
super(automata)
}
@Override
public void action() {
// GET : Use obj1
// POST :Set in automata state to State2
}
}
public class State2 extends State {
public State2(Automata automata){
super(automata)
}
@Override
public void action() {
// GET :Use obj1
// POST :Set in automata state to State1
}
}
public class Automata {
private State state1 = new State1(this);
private State state2 = new State2(this);
private State state = state1;
public void takeAction() {
state.action()
}
}
I have tried the following solutions:
- For GET store
obj1
in Automata and use getters and setters. For POST store states in Automata and use getters and setters. This approach will make the code unnecessarily long by using the getters and becomes hard to maintain with a changing list ofobj1
's and states. - Use private inner classes. Declare
State, State1
andState2
as private inner classes and access directlyobj1
and states. Hard to maintain and update simply because of length of file. Can not be shared with anotherAutomata
class. - Make fields public. I do not want to expose all of this fields.
- Use a singleton/static class approach for sharing
obj1
's
I am not very found of package private access.
In my design I am combining this pattern with the Template Method Pattern as a side information.
I know a one-fits-all approach does not exist, but what are common best practices in working with this pattern?
Aucun commentaire:
Enregistrer un commentaire