Object Creation

  • Thread starter Thread starter SK
  • Start date Start date
S

SK

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?
 
I have been not doing this in the methods themselves but will be interested
in what others have to say.

I worry about doing it in constructors for maintenance reasons.
 
It seems to me that if B is a singleton, then the logic for creating and
making sure there is only one instance belongs to the singleton. If you
push that logic to A, you could create more problems. For example, what
happens if A inadvertently creates more than one instance of the singleton?
Anyways, the design pattern from "Design Patterns" by the Gang of Four
describe a structure for a singleton class. In C# it would look like:

public class Singleton
{
private static Singleton _instance;

protected Singleton() { }

public static Singleton Instance()
{
if (_instance == null)
_instance = new Singleton();

return _instance;
}
}

Hope this helps.
 
Back
Top