gpt4 book ai didi

c# - 为采用参数/参数的类创建单例工厂

转载 作者:行者123 更新时间:2023-11-30 17:53:37 25 4
gpt4 key购买 nike

首先,我在 article 上阅读了这篇文章- 这基本上告诉我我根本不应该使用单例 -

Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.)

因为我需要参数,以及具有相同参数的相同实例 - 我得出结论,我需要一个工厂模式。

但是我无法在任何地方找到一个好的工厂模式实现。

Kindly direct me if you find any good c# singleton factory pattern implementation with parameters

好的,我会尝试在这里非常具体...希望这能解释我的情况。

欢迎使用替代方法。我只是组合了很多实现 - 我的理解可能有偏差。

所以我有一个类 'A'。它是一个用于连接数据库的类 - 数据库连接。

连接需要 4 个参数,约束是:

  1. 我需要有多个可能的连接 - 使用不同的数据库(参数不同)

  2. 我只需要一个特定连接的实例 - 一个参数相同的单例(据我所知)

  3. 我需要按照上述文章的工厂模型,还需要限制连接数、超时后关闭连接等。

在此基础上,我需要一个带有参数/参数的单例工厂......我假设

所以 A 类看起来像这样

<which access modifier ?> Class A {
private Class A(string hostname, string port, string username, string pw_hash) {
//create a new instance with the specified parameters
}
//other methods on the connection
protected void close() {
//close the connection
}
}

public class AFactory//should it inherit class A?? {

private IList<A> connections = new List<A>();
private AFactory()
{
//do something
}
private static readonly Lazy<AFactory> lazy
= new Lazy<AFactory>(() => new AFactory());

public static AFactory Instance { get { return lazy.Value; } }

public A getA(string hostname, string service, string username, string pw_hash)
{
foreach (A a in A)
{
if (a.hostname == hostname && a.service == service && a.username == username)
return a;
}
A d = new A(hostname, service, username, pw_hash);
connections.Add(d);
return d;
}

现在,只要类 A 构造函数是公共(public)的,它就可以很好地工作 - 但它有点违背了单例的目的。我需要做什么才能使此代码正常工作。

对于指定的参数,我只需要 1 个 A 类实例。

谢谢

因陀罗吉

最佳答案

工厂用于生成对象而不是管理对象。我认为数据库连接管理器更适合您的情况。您可以将管理器声明为单例。对于个人连接,您可以使用内部类/结构。

看下面的例子:

class DBConnectionManager
{
struct Connection
{
public string Hostname;
public string ServerName;
public string UserName;
public string Password;

public void Connect()
{
}

public void Close()
{
}
}

private static s_instance;
public static DBConnectionManager Instance
{
get {return s_instance; }
}

private List<Connection> m_connections;

public Connection GetConnection(string hostname, string serverName, string userName, string password)
{
// if already exist in m_connections
// return the connection
// otherwise create new connection and add to m_connections
}

public void CloseConnection(string hostname, string serverName, string userName, string password)
{
// if find it in m_connections
// then call Close()
}

public void CloseAll()
{
//
}
}

关于c# - 为采用参数/参数的类创建单例工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17141338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com