考虑以下代码
class SqlInstance
{
private SqlInstance()
{
}
public void Connect(string username, string password)
{
//connect
}
public void Disconnect()
{
//disconnect
}
//This method is not a singleton. Its one instance per key
public static SqlInstance GetInstance(string key)
{
return new SqlInstance();
}
}
class FileInstance
{
private FileInstance()
{
}
//no this is not a mistake. This connect has no parameters
private void Connect()
{
//connect
}
public void Disconnect()
{
//disconnect
}
//This method is not a singleton. Its one instance per key
public static FileInstance GetInstance(string key)
{
return new FileInstance();
}
}
class DataManager
{
SqlInstance GetSqlChannelInstance()
{
//if some logic
return SqlInstance.GetInstance("dev.1");
//if some other logic
return SqlInstance.GetInstance("dev.2");
//...and so on
}
FileInstance GetFileInstance()
{
//if some logic
return FileInstance.GetInstance("fil.1");
//if some other logic
return FileInstance.GetInstance("fil.2");
//...and so on
}
}
DataManager是一个包装样式类,调用者必须使用它来获取SqlInstance或FileInstance的实例。这里的问题是调用者可以直接调用类的GetInstance方法,而不是通过 DataManger 类。我们如何解决这个问题?具体来说,是否存在强制调用者通过DataManager的模式或机制?是否可以使两个Instance类仅对DataManager类“可见” 。
我知道将两个类设为DataManager类的内部类将有助于解决问题,但我想知道是否还有其他“更好”的方法可以做到这一点?
PS:请忽略类名和实现。这只是一个示例,并非来自任何现实生活中的代码。
语言是 C#