Factory Method Using Is/As Operator
- by Swim
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