c# - Is a private static list an appropriate way of limiting the set of instances of a class -
i trying avoid multiple instances of class being created same internal data. tried implementation separate class building mcode trying protect mcode constructor did not work have come implementation. wonder if design or better solution there may be?
public class mcode : iequatable<mcode> { private readonly static list<mcode> instances; public aenum ae { get; } public byte c { get; } public benum { 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; 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); } }
the motivations have multiple instances of classes contain same mcode property , i'd them using same read-only mcode instance.
what describing looks flyweight factory pattern. flyweights classes relatively small, , there finite number of "unique" objects, maintaining catalog of unique instances can reduce unnecessarily duplicated data in memory.
one example us state
. there 50 unique states, keeping collection of 50 states set of unique instances might make difference in system that, say, needs state every user record.
i separate class factory. make factory separate class, , make constructor mcode
internal
(instead of protected
.
i careful of equals
implementation. because 2 objects have same hash code not mean equal. may true in case since have finite number of objects can covered int
space, looks weird. implementing actual equals
logic (which have in list lookup) negate need duplicate gethashcode
method.
Comments
Post a Comment