c# - 如何使用单例进行继承

标签 c# inheritance singleton

我想知道如何从具有单例的类“BaseClient”继承,并能够在继承的类中使用来自基类单例的基本成员的相同实例。

public class BaseClient
{
    protected string _url;
    protected string _username;
    protected string _password;

    private static BaseClient _instance;
    private static readonly object padlock = new object();

    public static BaseClient Instance
    {
        get
        {
            lock (padlock)
            {
                if (_instance == null)
                {
                    _instance = new BaseClient(true);
                }
                return _instance;
            }
        }
    }

    public void SetInfo(string url, string username, string password)
    {
        _url = url;
        _username = username;
        _password = password;
    }

    public string GetVersion()
    {
        //MyService is a simple static service provider
        return MyService.GetVersion(_url, _username, _password);
    }
}

public class Advanced : BaseClient
{
    private static AdvancedClient _instance;
    private static readonly object padlock = new object();

    public static AdvancedClient Instance
    {
        get
        {
            lock (padlock)
            {
                if (_instance == null)
                {
                    _instance = new AdvancedClient(true);
                }
                return _instance;
            }
        }
    }

    public void DoAdvancedMethod()
    {
        MyService.DoSomething(_url, _username, _password);
    }
}

所以如果我使用 BaseClient.Instance.SetInfo("http://myUrl", "myUser", "myPassword");然后是 AdvancedClient.Instance.DoAdvancedMethod(),AdvancedClient 单例将使用与 BaseClient 单例相同的基本成员实例?

最佳答案

我总是发现使用通用实现此类解决方案要容易得多:

public class Singleton<T> where T : class
{

    protected Singleton()
    {
    }

    public static T Instance
    {
        get { return SingletonFactory.instance; }
    }

    public void SetInfo(string url, string username, string password)
    {
        ...
    }

    public string GetVersion()
    {
        ...
    }

    class SingletonFactory
    {

        internal static readonly T instance;

        static SingletonFactory()
        {
            ConstructorInfo constructor = typeof(T).GetConstructor(
                       BindingFlags.Instance | BindingFlags.NonPublic,
                       null, new System.Type[0],
                       new ParameterModifier[0]);

            if (constructor == null)
                throw new Exception(
                    "Target type is missing private or protected no-args constructor: type=" + 
                    typeof(T).FullName);
            try
            {
                instance = constructor.Invoke(new object[0]) as T;
            }
            catch (Exception e)
            {
                throw new Exception(
                    "Failed to create target: type=" + typeof(T).FullName, e);
            }
        }

    }

}

public class Advanced : Singleton<Advanced>
{
    ...
}

关于c# - 如何使用单例进行继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12962499/

相关文章:

java - 双重检查创建单例问题的方式

java - 避免全局状态而不困惑构造函数

javascript - 如何解决 node.js 中的模块缓存警告(单例问题)?

c# - Visual Studio 生成错误 :requested operation cannot be performed on a file with a user-mapped

c# - Log4Net 与应用程序洞察

C++ 虚函数返回类型

c++ - 在具有存储基成员的基类的派生类中使用/存储派生成员

c# - 当字符串中的字符更改时,RegEx 拆分/标记字符串

c# - 如何从 UWP map 上的 MapIcon 中删除点和尾部

c++如何从派生类实例调用模板化基类函数