I'm struggling to create a factory pattern where not the factory, but the classes determine which class needs to be used for creating the object. To make it more complicated than the normal factory pattern, the classes often need to create an instance of a subclass instead.
I would like to do something similar to this:
class Observation {
public int NumLegs;
public bool HasWings;
public NumChromosomes;
// etc.
}
class Organism {
public static Organism CreateByObservation(Observation obs) {
if (obs.numLegs == 4) return new Mammal.CreateByObservation(obs);
else if (obs.HasWings) return new Bird.CreateByObservation(obs);
// etc.
}
}
class Mammal: Organism {
public static override Mammal CreateByObservation(Observation obs) {
if (obs.NibblesALot) return new Rodent.CreateByObservation(obs);
else if (obs.Whinnies) return new Horse();
// etc.
}
}
class Rodent: Mammal {
public static override Rodent CreateByObservation(Observation obs) {
if (obs.Color == Colors.GRAY) return new Mouse();
else // ... you get the idea
}
}
// usage:
var myobservation = new Observation() { ... };
var myorganism = new Organism.CreateByObservation(myobservation);
tbName = myorganism.GetName();
For obvious reasons I'd like to encapsulate the determining code in the subclasses (Organism should know nothing about rodents), but since overriding static methods is not allowed in C# I can't use the above code.
What would be the best way to handle this?