我想知道如何从具有单例的类“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 单例相同的基本成员实例?