我有这个用于数据库连接的类实现。现在,这不是一个标准的 SQL 数据库。
我需要知道以下是否是一个好的实现,如果不是 - 为什么。
我需要一个带参数的单例类,这就是我设计它的方式。
class Connection
{
private string param1;
private string param2;
private static readonly IList<Connection> connections = new List<Connection>();
private Connection()
{
//Prevent instantiation
}
private Connection(string param1, string param2)
{
this.param1 = param1;
this.param2 = param2;
}
public static Connection getInstance(string param1, string param2)
{
foreach(Connection c in connections)
{
if(c.param1 = param1 && c.param2 == param2)
return c;
}
Connection new_conn = new Connection(param1, param2);
connections.Add(new_conn);
return new_conn;
}
}
它将按如下方式使用:
Connection c = Connection.getInstance(abc, xyz);
Connection d = Conn
*更新 - 现在可以了吗?*
class Connection
{
private string param1;
private string param2;
private static readonly ConcurrentDictionary<Tuple<string, string, string>, Connection> connections
= new ConcurrentDictionary<Tuple<string, string>, Connection>();
private Connection()
{
//Prevent instantiation
}
private Connection(string param1, string param2)
{
this.param1 = param1;
this.param2 = param2;
}
public static Connection getInstance(string param1, string param2)
{
Connection conn = activeConnections.GetOrAdd(new Tuple<string, string>
param1,param2), new Connection (param1, param2));
return conn;
}
}