I'm writing a wrapper around a class library that I have no control over. In this library is a class (let's call it Target
) that I want to ensure is only instantiated once, but it is not, in itself, a singleton. I thought of using the Singleton-Factory pattern like so:
internal sealed class SingletonFactory
{
private static readonly SingletonFactory manager = new SingletonFactory();
private readonly Target target;
private static SingletonFactory() { }
private SingletonFactory()
{
target = new Target();
target.Init("foo");
}
internal static SingletonFactory Instance
{
get { return manager; }
}
internal Target Target
{
get { return target; }
}
}
I can then do:
var targetInstance = SingletonFactory.Instance.Target;
I then thought of simplifying this by making the Factory completely static like this:
internal static class StaticFactory
{
private static readonly Target target;
private static StaticFactory()
{
target = new Target();
target.Init("foo");
}
internal static Target Target
{
get { return target; }
}
}
and access to the target instance becomes:
var targetInstance StaticFactory.Target;
I'm pretty sure this StaticFactory
is thread-safe, and provides global access to a single instance of the target class. Is there anything wrong with this that I haven't thought of?