c# - How to implement a custom class to have only one instance per value set (not singleton) -
this question has answer here:
i have custom class follows 2 enumerations:
public class mcode { public aenum { get; } public benum b { get; } public byte c { get; } //some constructors , methods }
i'd create 1 instance of each mcode (never create mcode if 1 exists same 3 values) , if ever create object contains mcode property, i'd ensure same instance property of previous object containing such mcode.
in terms of numbers: number of possible mcodes 100s number of references mcodes @ runtime 100s number of distinct mcodes in terms of values 3-10.
********************update***********************************
now tried use factory class follows:
public static class makemcode { private static list<mcode> instances; public static mcode instance(aenum ae, benum be, byte c) { var mc = instances.find(x=>x.gethashcode()==mcode.gethashcode(ae,be,c)); if (mc == null) { var newmc = new mcode(ae, be, c); instances.add(newmc); return newmc; } return mc; } }
where have implemented required gethashcode , static gethashcode suggest below (without second seemed need new mcode in order determine hashcode, why avoided using instances.contains)
but i'm unsure how implement constructors in mcode such uses makemcode.instance , protects against mcodes being created without calling makemcode.instance
you can create static list mcodespool, , add mcodes there on creation. differ codes overwriting gethashcode() method like
return (byte)aenum * 256 * 256 + (byte)benum * 256 * c;
so, when construct mcode can check if mcodespool contains mcode created hashcode.
p.s. use sorted collections if plan create tons of objects.
Comments
Post a Comment