I have a factory method as given below public class AutomobileFactory { Dictiona
ID: 644306 • Letter: I
Question
I have a factory method as given below
public class AutomobileFactory
{
Dictionary<string, ICar> internalFactory = new Dictionary<string, ICar>();
public AutomobileFactory()
{
internalFactory.Add("fiat",new Fiat());
internalFactory.Add("ford", new Ford());
}
public ICar Create(string carType)
{
return internalFactory[carType];
}
}
It is a very humble code. Now, I referred Factory pattern with generics. But I am not able to understand what extra this generic approach can offer.
QUESTION
What is the shortcoming of the above given factory when compared to the generic factory?
Explanation / Answer
Generic versions of algorithms generally provide type safety. Your version accepts a string to specify the type. That string could be anything, and the compiler cannot check it for you to see if it is correct.
If you specify a type in your version that you haven't registered, you won't know that until the program actually executes, where it will either cause an error, or do nothing. In the generic version you linked, you don't even have to register the types; it will just use whatever type you provide it.
For what it's worth, the article you linked seems to describe a lot of ceremony for not much benefit. "I know; I'll write the mother of all factories so that I never have to write another factory again." Or, you could, y'now, just instantiate the type you need, and get on with it.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.