I'm trying to succinctly describe when to use a factory, for both myself and my team. I ran across the following related questions, which helped somewhat:
- When to use factory patterns?
- (useful pdf link is broken)
- How do you create your Factories?
- (more 'how' rather than 'when')
- What is your threshold to use factory instead of a constructor to create an object?
- (some general answers)
- Factory Pattern. When to use factory methods?
- (more about factory methods than factory classes)
- When to use Factory method pattern?
- (again more about factory methods)
Based on these links, and a bunch of other sources (listed at the bottom), I've come up with the following:
When to use the abstract factory pattern:
- when you use an interface var or the 'new' operator
- e.g. User user = new ConcreteUserImpl();
- and the code you are writing should be testable / extensible at some point
Explanation:
- interfaces by their very nature imply multiple implementations (good for unit testing)
- interface vars imply OCP- and LSP-compliant code (support sub-classing)
- use of the 'new' operator breaks OCP/DI, because highly-coupled classes are hard to test or change
"Do I create a factory for every object type? That seems excessive."
- no, you can have one (or a few) factories that produce a lot of (usually related) object types
- e.g. appFactory.createUser(); appFactory.createCatalog(); etc.
When NOT to use a factory:
- the new object is very simple and unlikely to be sub-classed
- e.g. List list = new ArrayList();
- the new object is not interesting to test
- has no dependencies
- performs no relevant or long-running work
- e.g. Logger log = new SimpleLogger();
References:
- http://googletesting.blogspot.com/2008/08/where-have-all-singletons-gone.html
- http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/
- http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/
- http://en.wikipedia.org/wiki/Dependency_Injection
- http://en.wikipedia.org/wiki/Open_Closed_Principle
- http://en.wikipedia.org/wiki/Liskov_substitution_principle
My question is: is my summary accurate, and does it make sense? Is there anything I've overlooked?
Thanks in advance.