In my project, I have a bunch of value objects that look like this:
public class ObjectState : System.Object
{
private readonly DirectionOption direction;
private readonly Feature feature;
private readonly RotationOption rotation;
// access properties
}
In my code, I create instances of this class, but I would like to avoid having to create new instances everywhere and instead reference one instance per combination of Direction
, Feature
and Rotation
. How do I do that properly?
My solution looks like this:
private static TileStateEnabler dummy = null;
private static Dictionary<int, TileStateEnabler> referenceSet = null;
public static TileStateEnabler Get(DirectionOption direction, Feature feature, RotationOption rotation)
{
if (dummy == null)
{
dummy = new TileStateEnabler(direction, feature, rotation);
}
else
{
dummy.Direction = direction;
dummy.Feature = feature;
dummy.Rotation = rotation;
}
int hashcode = dummy.GetHashCode();
if (referenceSet.ContainsKey(hashcode))
{
return referenceSet[hashcode];
} else
{
var enabler = new TileStateEnabler(direction, feature, rotation);
referenceSet.Add(hashcode, enabler);
return enabler;
}
}
Are there better solutions? I don’t like the dummy and the set being static because they stick around even after not needing them anymore.