代码之家  ›  专栏  ›  技术社区  ›  gwizardry

私有静态列表是限制类实例集的适当方法吗

  •  0
  • gwizardry  · 技术社区  · 7 年前

    我试图避免使用相同的内部数据创建类的多个实例。我尝试了一个使用单独类来构建MCode的实现,但试图保护MCode构造函数没有起作用,所以我回到了这个实现。我想知道这是一个好的设计还是有更好的解决方案?

    public class MCode : IEquatable<MCode>
    {
    
        private readonly static List<MCode> Instances;
        public AEnum AE { get; }
        public byte C { get; }
        public BEnum BE { get; }
    
        public static MCode GetMCode(AEnum ae, BEnum be, byte c)
        {
                if (Instances==null)
                {
                    Instances = new List<MCode>();
                    var newmc = new MCode(ae, be, c);
                    Instances.Add(newmc);
                    return newmc;
                }
    
                var mc = Instances.Find(x => x.Equals(ae, be, c));
    
                if (mc == null)
                {
                    var newmc = new MCode(ae, be, c);
                    Instances.Add(newmc);
                    return newmc;
                }
                return mc;
        }
    
        protected MCode(AEnum ae, BEnum be, byte c)
        {
            AE = ae;
            BE = be;
            C = c;
        }
    
        public new bool Equals(MCode mc)
        {
            return (GetHashCode() == mc.GetHashCode());
        }
    
        public new bool Equals(AEnum ae, BEnum be, byte c)
        {
            return (GetHashCode() == GetHashCode(ae, be, c));
        }
    
        public new int GetHashCode()
        {
            return ((byte)AE * 256 * 256 + (byte)BE * 256 * C);
        }
    
        public static int GetHashCode(AEnum ae, BEnum be, byte c)
        {
            return ((byte)ae * 256 * 256 + (byte)be * 256 * c);
        }
    }
    

    2 回复  |  直到 7 年前
        1
  •  4
  •   D Stanley    7 年前

    你所描述的看起来是一个 Flyweight Factory pattern 。Flyweight是相对较小的类,并且“唯一”对象的数量有限,因此维护唯一实例的目录可以帮助减少内存中不必要的重复数据。

    一个例子是 US State 。只有50个唯一状态,因此将50个状态的集合保留为一组唯一实例可能会对每个用户记录都需要一个状态的系统产生影响。

    我也会把班级和工厂分开。使工厂成为一个单独的类,并使构造函数 MCode internal protected .

    我也会小心你的 Equals int 等于 逻辑(您在列表查找中已经有了)也会消除重复的需要 GetHashCode

        2
  •  2
  •   InBetween    7 年前

    public class MyType
    {
        private readonly static Dictionary<int, MyType> instances
           = new Dictionary<int, MyType>();
    
        public static MyType CreateNew(int id)
        {
            if (instances.TryGetValue(id, out var instance)
                return instance;
    
            return new MyType(id);
        }
    
        private MyType(int id) { ... }
    
        public int UniqueId { get; }
    }
    

    如果您的唯一标识符比 int