views:

55

answers:

1

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.

+3  A: 

Use generics. Code/PseudoCode:

class UniquePattern<T>
{
    private static Dictionary<int, T> idLookup;
    ....
    private T(id) {...}
    public static T Get(id) 
    {
       ...
    }
}
Aliostad
There's a `where T : new()` type constraint for a parameter-less constructor, but there are no such type parameter constraints for constructors with specific parameters... i.e. `where T : new(int)` isn't valid C#. -- That said, generics seem to be the way to go here.
stakx
each time i rediscover the "where" syntax and each time i'm amazed :) @stakx oww i talked too fast, then
samy
Yes, you are right. I had used new() but I was surprised it does not support parameterful constructor. I have removed it.
Aliostad