The singleton pattern

  • Thread starter Thread starter Jonathan Rea
  • Start date Start date
J

Jonathan Rea

Hey,

I currently have the following code :

public sealed class FFManager
{
// Singleton pattern - single initialisation of FFManager for the
application
private static readonly FFManager instance = new FFManager();
private static bool FinalisePerformed = false;
public static FFManager Instance
{
get
{
return instance;
}
}
private FFManager()
{
// bla bla bla
}
}

The problem that I have is that the singleton class reads in a load of
definitions from a file to create many instances of a few classes. These
classes are required to talk to each other through the FFManager class in
order to configure themselves. The trouble comes in the fact that when
instance = new FFManager() is called, the created sub-classes call
FFManager.Instance. At this point the instance object in FFManager isnt
generated, and therefore an infinate loop is created (it keeps calling
instance = new FFManager(); ) and the program has a Stack Overflow
exception.

Is there a neat (or any) way round this, cos im damned if i can see it....

Many thanks
Jon
 
Jon,

You can use a static constructor to create the new instance, and seperate
the code which references the instance into an additional initialisation
method, eg:
private static FFManager()
{
instance = new FFManager();
instance.InitialiseTheOtherStuff();
}

HTH,
Chris.
 
Jonathan Rea said:
I currently have the following code :

public sealed class FFManager
{
// Singleton pattern - single initialisation of FFManager for the
application
private static readonly FFManager instance = new FFManager();
private static bool FinalisePerformed = false;
public static FFManager Instance
{
get
{
return instance;
}
}
private FFManager()
{
// bla bla bla
}
}

The problem that I have is that the singleton class reads in a load of
definitions from a file to create many instances of a few classes. These
classes are required to talk to each other through the FFManager class in
order to configure themselves. The trouble comes in the fact that when
instance = new FFManager() is called, the created sub-classes call
FFManager.Instance. At this point the instance object in FFManager isnt
generated, and therefore an infinate loop is created (it keeps calling
instance = new FFManager(); ) and the program has a Stack Overflow
exception.

Hmmm... I'm slightly surprised that it's recursing. I'd have expected
Instance to return null when another class tried to use it while
FFManager is already initializing.
Is there a neat (or any) way round this, cos im damned if i can see it....

Sooner or later you'll have to get the classes to be able to initialise
without using the singleton property. You could give their constructors
a parameter which is an instance of the singleton, and then pass
"this" from the FFManager constructor everywhere.
 
Back
Top