jameszhao00
jameszhao00

Reputation: 7301

Design Pattern for Unique Object Per ID system

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.

Upvotes: 2

Views: 915

Answers (1)

Aliostad
Aliostad

Reputation: 81680

Use generics. Code/PseudoCode:

class UniquePattern<T>
{
    private static Dictionary<int, T> idLookup;
    ....
    private T(id) {...}
    public static T Get(id) 
    {
       ...
    }
}

Upvotes: 3

Related Questions