抽象基类强制每个派生类为Singleton

thi*_*eek 9 c# oop ooad

如何创建一个抽象类来强制每个派生类为Singleton?我用C#.

小智 6

这是行不通的,因为单身人士需要一个静态访问,而不能被强制.

for singletonimplemention + examples请参阅:在C#中实现Singleton模式


Ste*_*ven 5

当您想要进行编译时检查时,这是不可能的。通过运行时检查,您可以做到这一点。这并不漂亮,但这是可能的。这是一个例子:

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()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 那不是单身人士。使用单例模式,您对“getInstance”的调用将始终成功。您的提议实际上只是一个运行时检查,它不提供单例模式的任何好处。 (3认同)