Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Object Creation

i have a class A and  I have a singleton class B.
i am accessing the object of B from A and is using B's method from most of the methods of A.
Is it good practice to create the singleton Bs instance in the constructor of A or in some methods of A?

SK
Friday, August 27, 2004

Not 100% sure I understand the question, but the (sole) instance of a singleton class B should be created in its GetInstance() method or equivalent, like this:

class B
{
  private static B _instance;
  private B() {} // disallow direct instanciation from elsewhere
  public static B GetInstance()
  {
      if( _instance == null ) _instance = new B();
      return _instance;
  }
}

Girb
Friday, August 27, 2004

Here u have this method GetInstance in B. MY question is Should i call this .GetInstance from the constructor of A....??

Hope i am clear now.

SK
Friday, August 27, 2004

It's up to you. Creating a new object has some overhead, so if you may not use it at some point (say it depends on something else), just wait to create it until you need it really. Then any subsequent time the overhead of constructing the object is gone.

Sort of understand?

Ian

Ian Sefferman
Friday, August 27, 2004

I make all the methods and member data of B static, give B a static constructor, and therefore don't explicitly instantiate B from A: have a static B() ensures that B is constructed automatically when any of its static methods is invoked; note that I can't pass parameters to the static B constructor.

Christopher Wells
Friday, August 27, 2004

*  Recent Topics

*  Fog Creek Home