I have the follow classes (C# for example)
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
Is there a design pattern (was doing inheritance but that got a bit messy) that can remove all that duplicate code?
The above functionality guarantees that only 1 instance of A/B/... exists for an id.