I am trying to implement a state (of type A
) machine which have multiple states (A1, A2, ..
so on). Each state implements method in A
(for simplicity consider just foo()
). Methods like foo()
do their job and then change the state to the next state as per the state machine.
Interface A
and all their implementing classes are used by class B
via composition. B
maintains a current state in currentA
, and exposes a method setCurrentA()
to update its current state. The same method is used by A1, A2, ..
to change the state of B.
public interface A {
void foo();
}
class A1 implements A {
private final B b;
public A1(B b) {
this.b = b;
}
public void foo() {
b.setCurrentA(b.getA2());
b.baz();
}
}
class A2 implements A {
...
}
public class B {
private final A a1;
private final A a2;
private A currentA;
public B() {
a1 = new A1(this);
a2 = new A2(this);
currentA=a1;
}
void setCurrentA(A a) {
currentA = a;
}
A getA2() {
return a2;
}
void baz(){
...
}
Is the above design good and acceptable? Isn’t that a cyclic dependency (B
having dependencies on A, A1, A2, ..
as well as A, A1, A2..
having dependency on B).
If yes, what is the standard/better way of doing it?
If no, why?
Thanks you so much!
hrishi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.