Brian J. Sayatovic wrote:
> I have what I believe is a circular dependency:
>
> public class State {
> public static final State INITIAL_STATE = loadState(0);
> protected static State loadState(int value) {
> Persistence persistence = Persistence.getDefaultInstance();
> return persistence.getState(0);
> }
> }
>
> public class Persistence {
> public static Persistence getDefaultInstance() {
> // ... *standard* singleton pattern
> }
> public State getState(int value) {
> // ... SELECT * FROM STATES WHERE STATE_VALUE=?
> }
> }
>
> I believe that because the Persistence class references the State
> class (as a return type), that it wants to load and initialize the
> State class first. However, the State class also needs the
> Persistence class's default instance to be set so that it can load
> it's static members from the DB.
>
> The bit of code you don't see here is that I'm not really using the
> standard singleton pattern. Instead, I have a 'main' class that
> constructs a Persistence instance and sets it as the default instance
> of Persistence. So when that first instance is being constructed, and
> thus, it's class is being loaded, I'm guessing it also tries to load
> the State class. However, the state class tries to access the default
> instance which has not yet been set.
>
> I'm drawing a blank. How can I design around this?
You may not need to design around it, but if you want to do (I would)
then one alternative would be to make State an interface, and have
Persistence.getState(int) return an instance of a nested class that
implements State. In my opinion, a tight coupling such as the one you
have shown needs to be either loosened or coallesced, and my suggestion
does both.
John Bollinger