Factory Method Using Is/As Operator

Posted by Swim on Stack Overflow See other posts from Stack Overflow or by Swim
Published on 2010-06-02T15:48:32Z Indexed on 2010/06/02 15:54 UTC
Read the original article Hit count: 139

Filed under:
|
|

I have factory that looks something like the following snippet. Foo is a wrapper class for Bar and in most cases (but not all), there is a 1:1 mapping. As a rule, Bar cannot know anything about Foo, yet Foo takes an instance of Bar. Is there a better/cleaner approach to doing this?

public Foo Make( Bar obj )
{
    if( obj is Bar1 )
        return new Foo1( obj as Bar1 );
    if( obj is Bar2 )
        return new Foo2( obj as Bar2 );
    if( obj is Bar3 )
        return new Foo3( obj as Bar3 );
    if( obj is Bar4 )
        return new Foo3( obj as Bar4 ); // same wrapper as Bar3
    throw new ArgumentException();
}

At first glance, this question might look like a duplicate (maybe it is), but I haven't seen one exactly like it. Here is one that is close, but not quite:

http://stackoverflow.com/questions/242097/factory-based-on-typeof-or-is-a

© Stack Overflow or respective owner

Related posts about c#

Related posts about best-practices