After some years of experience in the field, it seems to me that the Factory pattern is one of the less interesting and useful patterns around when not writing frameworks or libraries.
I'm not saying that Factory pattern is unnecessary. For example, the W3C Document
interface serves as a factory for various XML nodes (elements, attributes, text, ...). The AST
class in the Eclipse JDT serves as a factory for ASTNode
s like Assignment
, MethodDeclaration
, etc. I can find many other framework/library examples.
But most of the time, in plain client code, I never feel the need to use Factory pattern. You don't care where the objects come from or how they are created. You just wire up objects through their interfaces with Dependency Injection and afterwards these objects can 'Spring' into life, in a manner dependent on the environment (e.g. new
by hand in simple local test, bean container in JEE environment, ...). But never by a Factory, like ArticleFactory.createArticle()
.
I realize that Spring for example can be considered to be a bean 'factory', but the Spring bean factory is very generic, and the implementation of Factory I'm talking about should have a specific interface and is somehow restricted to creating members of a predefined 'family' of objects.
I also noticed that Factory, Composite, and Visitor often go hand in hand, where the Factory creates a set of (domain-)related objects that a Visitor can traverse. Again, typical stuff for frameworks but not client code.
Therefore, my question is: are there situations, outside of frameworks, where you (would) use Factory pattern instead of plain interfaces and dependency injection? And if so, is there an associated Visitor?