Choose class type without switch
Let's say that I have
Code:
public enum fruitType: byte
{
apple,
orange,
banana,
durian,
}
fruitType type = fruitType.apple;
Fruit myFruit = null;
switch(fruitType)
{
case(fruitType.apple):
myFruit = new Apple();
break;
case(fruitType.banana):
myFruit = new Banana();
break;
case(fruitType.orange)
myFruit = new Orange();
break;
}
Above, I am trying to create a specific Fruit object in real time based on the value of type. Is there a way to do this without using a switch or an if statement?
Re: Choose class type without switch
Hrm, interesting question. I was considering declaring a constructor delegate (let's call it FruitConstructor) and they creating a Dictionary<fruitType, FruitConstructor> to associate a fruitType with it's conjugate constructor. However, this is not supported natively (see link).
I am not certain that it is possible to do it any cleaner then you've got. Anyone know better?
Re: Choose class type without switch
Well I suppose you could have a factory for each type, however the case statement allows you to return multiple types of object from a single factory method.
Google the "class factory" to understand more.
Re: Choose class type without switch
You're not going to be able to do it without using a lot of reflection, though it is possible. Here's an overview of one approach: http://www.codeproject.com/Articles/...with-C-and-NET
You can pick the parts that you need. You probably don't need to collect *all* of the assembly's classes into the dictionary, just your Fruit types, so it should be less cumbersome. I would almost prefer writing some code to auto-generate the switch statement though.
Re: Choose class type without switch
Depending on what you want to achieve, you could also use the Prototype Pattern. The gist of it is: you create a prototypical instance of the given subtype, store it in an builder object (a factory, or something else), and then use the abstract interface of the Prototype base class to clone the prototypical instance when a new object is required. Essentially, you replace the enum-based configuration with an object-based configuration. Usually, the cloned instance is then initialized via setup methods/properties (since it's not created by invoking a constructor).
Prototype pattern helps avoid coding the factory class hierarchy - you end up with just the product hierarchy.