DayTimeCoder
DayTimeCoder

Reputation: 4332

A Singleton should be inheritable or not?


A Singleton should be inheritable or They should not be ?

According to Gof "when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code."

but then why do i see Sealed and Private constructor examples on MSDN

Upvotes: 2

Views: 428

Answers (2)

Ivan
Ivan

Reputation: 1284

In my projects, I use an Ambient Context implementation from Mark Seemanns book Dependency Injection in .NET. The main point of use of that pattern is that always when you are asking for Current instance, there has to be something and also Context can be switched by other implementation. F.E.

public class TimeContext
{
    private static TimeContext _instance;

    public static TimeContext Current
    {
        get
        {
            if (_instance == null)
            {
                _instance = new DefaultContext();
            }
            return _instance;
        }
        set
        {
            if (value != null)
            {
                _instance = value;
            }
        }
    }
    public abstract DateTime GetDateTime();
}

And concrete implementation of context should be like:

public class DefaultContext : TimeContext
{
    public DateTime GetDateTime()
    {
        return DateTime.Now();
    }

}

Upvotes: 2

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

I think you're mixing two different things here. The singleton pattern calls for a single instance that is used by all callers. Inheritance just means I can share common logic between a class hierarchy. This, I feel, is an implementation of the singleton pattern: (ignore the lack of locking/thread safety, for the example's sake)

public class Singleton
{
    private static Singleton _instance;
    public static Singleton Instance
    {
         get 
         { 
            if (_instance == null)
            {
                 // This is the original code.
                 //_instance = new Singleton();

                 // This is newer code, after I extended Singleton with
                 // a better implementation.
                 _instance = new BetterSingleton();
            }
            return _instance;
         }
    }

    public virtual void ActualMethod() { // whatever }
}

public class BetterSingleton : Singleton
{
    public override void ActualMethod() { // newer implementation }
}

We still have a singleton, accessed through the Singleton class's static Instance member. But the exact identity of that instance can be extended through subclassing.

Upvotes: 2

Related Questions