Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract base class to force each derived classes to be Singleton

Tags:

c#

oop

ooad

How do I make an abstract class that shall force each derived classes to be Singleton ? I use C#.

like image 489
this. __curious_geek Avatar asked May 18 '10 07:05

this. __curious_geek


People also ask

Can an abstract class be a Singleton?

The Singleton pattern requires a private constructor and this already makes subclassing impossible. You'll need to rethink your design. The Abstract Factory pattern may be more suitable for the particular purpose. The purpose of the private constructor in the Singleton is to prevent anyone else instantiating it.

Can a derived class be Singleton?

Yes you can. Keep base class constructor protected (and not private). Then derived class can be instantiated but base class cannot be (even inside function definitions of derived class).

Can abstract class be used in derived class?

A class derived from an abstract base class will also be abstract unless you override each pure virtual function in the derived class. The compiler will not allow the declaration of object d because D2 is an abstract class; it inherited the pure virtual function f() from AB .

How do you convert a class to Singleton?

To create a singleton class using Lazy Initialization method, we need to follow the below steps: Declare the constructor of the class as private. Create a private static instance of this class but don't initialize it. In the final step, create a factory method.


1 Answers

When you want to enfore compile time checking, this is not possible. With runtime checking you can do this. It's not pretty, but it's possible. Here's an example:

public abstract class Singleton
{
    private static readonly object locker = new object();
    private static HashSet<object> registeredTypes = new HashSet<object>();

    protected Singleton()
    {
        lock (locker)
        {
            if (registeredTypes.Contains(this.GetType()))
            {
                throw new InvalidOperationException(
                    "Only one instance can ever  be registered.");
            }
            registeredTypes.Add(this.GetType());
        }
    }
}

public class Repository : Singleton
{
    public static readonly Repository Instance = new Repository();

    private Repository()
    {
    }
}
like image 158
Steven Avatar answered Sep 28 '22 04:09

Steven