Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
    
Needing to modify the parent class when creating a new derived class is a poor code smell. –  James Youngman Mar 19 '12 at 11:28

1 Answer 1

up vote 5 down vote accepted

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.

share|improve this answer
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. –  Martijn Verburg Mar 19 '12 at 9:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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