Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define an abstract class for all derived Singletons in this way?

This is my abstract class which must be derived each time I want to make a Singleton:

public abstract class Singleton<T> where T : Singleton<T>
{
    private static readonly Lazy<T> _instance = new Lazy<T>(() =>
    {
        var constructor = typeof(T).GetConstructor(BindingFlags.NonPublic |
            BindingFlags.Instance, null, new Type[0], null);

        return (T)constructor.Invoke(null);
    });
    public static T Instance { get { return _instance.Value; } }
    public Singleton() { }
}

So, every time I need to follow the Singleton design pattern, I can just make this:

sealed class Server : Singleton<Server>
{
    private Server() { }
    ...
}

Is this completely right, and, if not, why?

Edit:

  • Added private constructor on derived class example and invoking on abstract base.

Edit:

  • Reworked type parameter initialization.
like image 387
AgentFire Avatar asked Nov 07 '11 13:11

AgentFire


People also ask

Can a Singleton be abstract?

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 abstract class be Singleton in Java?

Most other languages simply do not allow defining abstract singleton class methods (for example, static methods in TypeScript, C++, Java, C#, and more are not allowed to be abstract).

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).

Why you should not use singletons?

Singletons leave a trail of confusion Bugs might stay hidden even when you're testing. It's very difficult to write unit tests for code that uses singletons because it is generally tightly coupled with the singleton instance.


1 Answers

No you can't because when you want to use new T() you should have a public constructor for it, and it's different from singleton definition. because in singleton you should have a private constructor, and in this case (public one) everyone can create new instance of your object and it's not a singleton.

like image 126
Saeed Amiri Avatar answered Sep 22 '22 06:09

Saeed Amiri