0

I have two singleton classes, lets call them class A and class B.

The classes look like such.

class A
{
  private static A instance;

   private A(int timeout)
   {
     init();
   }

    public static A getInstance(int timeout)
    {
      if(instance == null)
      {
        instance = new A(timeout);
      }
      return instance;
    } 

    private void init()
    {
      new Monitor().sendMonitorStatus();
    }
}

and for class B

class B
{
private static B instance;

   private B(A a)
   {

   }

    public static B getInstance(A a)
    {
        if(instance == null)
        {
            instance = new B(a);
        }
        return instance;
    }
}

Then there is a class named Monitor as well that looks as such.

class Monitor
{
  public void sendMonitorStatus()
  {
    B.getinstance(A.getinstance(10));
  }
}

The problem as you can see, is that I get a stackoverflow since it keeps a cycle of a call to B then calling A which calls B which calls A..., is there anyway to solve this problem without a redesign or is the only way to solve this cycle causing this error to redesign how the classes work?

jgr208
  • 2,896
  • 9
  • 36
  • 64

1 Answers1

2

To create an instance of A, you need to call Monitor::sendMonitorStatus. To call Monitor::sendMonitorStatus, you need an instance of A. You have a dependency cycle.

You need to redesign this. Exactly how – it depends on what you want to achieve.

Karol S
  • 9,028
  • 2
  • 32
  • 45
  • Yup, was afraid there was no way around it. Well `A` populates a list of objects that are created in another class and `B` sends the message of these objects to another class, in a message protocol. I may need to add another class then it sounds like to get rid of this dependency on each other. – jgr208 Jul 23 '15 at 18:04