3

I have seen this at many places. a Parent class has a static method to create objects of the right subclass and at times we have a dedicated factory class with instance methods to create object of various subclasses.

Which one is used in which scenario ?

Like static factory methods of InetAddress in java.net to create subclasses of InetAddress Vs BorderFactory class to create various Borders.

1
  • Needing to modify the parent class when creating a new derived class is a poor code smell. Mar 19, 2012 at 11:28

1 Answer 1

5

The second one; the separate class. That separate class should also have an interface. The reason is that this is the option that allows swapping the factory most easily, which is good for lowering coupling and for testability.

1
  • 1
    It might also be worth looking at Inversion of Control, or actually its close cousin Dependency Injection which some argue is a cleaner, more pluggable way to get the same behaviour. Mar 19, 2012 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.