Singletons and inheritance
For a long time, when people have asked about having inheritance and singletons, I've stated flatly that a singleton can't be derived from. It stops being a singleton at that point. Even if the class is internal and you can prove that no other classes in the assembly do derive from the singleton and break the pattern's effect, it's still not a genuine singleton.
It was only when I was thinking about one of the comments about my enhanced enums proposal that I realised there's an alternative approach. You can derive from a singleton as nested types of the Singleton itself and still keep the private constructor. That means that the singleton nature is still contained within the body of the text which declares the singleton class, even though that text actually declares more classes. Indeed, the singleton itself can even be abstract. Here's an example:
using System;
public abstract class DataProvider
{
static DataProvider instance = CreateDataProvider();
public static DataProvider Instance
{
get { return instance; }
}
private DataProvider() {}
public abstract void Connect();
static DataProvider CreateDataProvider()
{
if (DateTime.Now.DayOfWeek==DayOfWeek.Sunday)
{
return new OracleProvider();
}
else
{
return new SqlServerProvider();
}
}
class OracleProvider : DataProvider
{
public override void Connect()
{
Console.WriteLine ("Connecting to Oracle");
}
}
class SqlServerProvider : DataProvider
{
public override void Connect()
{
Console.WriteLine ("Connecting to SQL Server");
}
}
}
I'm not suggesting you should actually use a singleton for a data provider like this -
it just seemed like a simple example to demonstrate the point.
It is easy to validate that the singleton only allows one instance of DataProvider
to ever be constructed. (This version isn't fully lazy, but that could be added if desired.)
It looks like I'll have to revise my statement about inheritance from now on...