Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory Pattern: Enums or Types?

When implementing a factory or simple factory, what would go against using a Type instead of an Enum to specify the class to instantiate?

For example

public class SimpleFactory
{
 public static ITest Create(Type type)
 {
  if (type == typeof(ConcreteTest1))
   return new ConcreteTest1();
  if (type == typeof(ConcreteTest2))
   return new ConcreteTest2();

  throw new Exception("Invalid type");
 }
}
like image 655
Castrohenge Avatar asked May 08 '09 16:05

Castrohenge


1 Answers

Using an enum is more restrictive, which means that it is less likely that the user will try to use your factory with an unsupported type.

I find that it's good to do everything possible when defining an API to discourage usage patterns that will cause exceptions to be thrown. Allowing "Type" in this case opens up millions of ways to call your function that will result in:

throw new Exception("Invalid type");

Using an enum would eliminate this. The only way an enum would throw would be if the user did something noticably wrong.

like image 113
Reed Copsey Avatar answered Sep 28 '22 05:09

Reed Copsey