【问题标题】:Design Pattern for Unique Object Per ID system每个 ID 系统的唯一对象的设计模式
【发布时间】:2010-10-05 20:56:24
【问题描述】:

我有以下课程(例如 C#)

class A
{
    private static Dictionary<int, A> idLookup;
    ....
    private A(id) {...}
    public static A Get(id) 
    {
        //does some magic
        if (...) { return idLookup[id]; }
        else { A a = new A(id); idLookup[a.id] = a; return a; }
    }
}

class B
{
    private static Dictionary<int, B> idLookup;
    ....
    private B(id) {...}
    public static B Get(id) 
    {
        //does some magic
        if (...) { return idLookup[id]; }
        else { B b = new B(id); idLookup[b.id] = b; return b; }
    }
}
... and so on

是否有可以删除所有重复代码的设计模式(正在进行继承但有点混乱)?

上述功能保证一个 id 只存在 1 个 A/B/... 实例。

【问题讨论】:

  • 没有那么多重复代码。您可以编写一个更专业的字典以使其更容易,然后它就会是单行的。
  • 所以我认为这是一个单线程程序?
  • @Kirk Wool,是的......这东西在多线程代码中会非常失败。
  • 现在我想起来了,最好有一个管理器类来处理创建/获取

标签: c# design-patterns inheritance


【解决方案1】:

使用泛型。代码/伪代码:

class UniquePattern<T>
{
    private static Dictionary<int, T> idLookup;
    ....
    private T(id) {...}
    public static T Get(id) 
    {
       ...
    }
}

【讨论】:

  • 对于无参数构造函数有一个where T : new() 类型约束,但是对于具有特定参数的构造函数没有这样的类型参数约束......即where T : new(int) 不是有效的C#。 -- 也就是说,泛型似乎是这里的出路。
  • 每次我重新发现“where”语法并且每次我都感到惊讶:) @stakx oww 我说得太快了,然后
  • 是的,你是对的。我曾经使用过 new() 但我很惊讶它不支持有参数的构造函数。我已将其删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多