如何使用与singleton类的接口

use*_*018 7 c#

当我解决Singleton Vs Static类之间的差异时,我遇到了一个问题,即我们可以在singleton类中继承一个接口,并且可以通过接口调用singleton来实现多个实现.

我希望通过一个很好的例子进行一些代码演示,如何通过单例而不是静态来实现面向对象.

谢谢,

Gro*_*roo 4

尽管很难说出您到底指的是什么,但您可能指的一种模式是Multiton 模式,您可以在其中将命名实例的映射作为键值对进行管理。

这基本上是一个工厂,但每个实例只创建一次:

我对维基百科的示例进行了一些修改,以表明您甚至可以从单例类派生,只要您的具体实现是私有的并且位于原始类中:

class FooMultiton
{
    private static readonly Dictionary<object, FooMultiton> _instances =
        new Dictionary<object, FooMultiton>();

    // this is the classic good old singleton trick (prevent direct instantiation)
    private FooMultiton()
    { }

    // you can also have private concrete implementations, 
    // invisible to the outside world
    private class ConcreteFooMultitonOne : FooMultiton
    { }

    public static FooMultiton GetInstance(object key)
    {
        lock (_instances) 
        {   
            FooMultiton instance;

            // if it doesn't exist, create it and store it
            if (!_instances.TryGetValue(key, out instance))
            {
                // at this point, you can create a derived class instance
                instance = new ConcreteFooMultitonOne();
                _instances.Add(key, instance);
            }

            // always return the same ("singleton") instance for this key
            return instance;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,一般来说,如果单例不是静态类,它可以实现您想要的任何接口。单例模式唯一阻止的是单例类的多个实例的实例化,但这并不意味着您不能完全用其他东西替换实现。

例如,如果您有一个不是静态类的单例:

interface ICanTalk
{
    string Talk();
}

class Singleton : ICanTalk
{
    private Singleton() { }

    private static readonly Singleton _instance = new Singleton();
    public static Singleton Instance
    { get { return _instance; } }

    public string Talk()
    { return "this is a singleton"; }
}
Run Code Online (Sandbox Code Playgroud)

您还可以有许多不同的实现:

class OtherInstance : ICanTalk
{
    public string Talk()
    { return "this is something else"; }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以自由选择你想要的任何实现,但只获得该类的一个实例Singleton

ICanTalk item;

item = Singleton.Instance;
item = new OtherInstance();
item = new YetAnotherInstance();
Run Code Online (Sandbox Code Playgroud)