oop - When to use the abstract factory pattern? -
i'm trying succinctly describe when use factory, both myself , team. ran across following related questions, helped somewhat:
- when use factory patterns?
- (useful pdf link broken)
- how create factories?
- (more 'how' rather 'when')
- what threshold use factory instead of constructor create object?
- (some general answers)
- factory pattern. when use factory methods?
- (more factory methods factory classes)
- when use factory method pattern?
- (again more factory methods)
based on these links, , bunch of other sources (listed @ bottom), i've come following:
when use abstract factory pattern:
- when use interface var or 'new' operator
- e.g. user user = new concreteuserimpl();
- and code writing should testable / extensible @ point
explanation:
- interfaces nature imply multiple implementations (good unit testing)
- interface vars imply ocp- , lsp-compliant code (support sub-classing)
- use of 'new' operator breaks ocp/di, because highly-coupled classes hard test or change
"do create factory every object type? seems excessive."
- no, can have 1 (or few) factories produce lot of (usually related) object types
- e.g. appfactory.createuser(); appfactory.createcatalog(); etc.
when not use factory:
- the new object simple , unlikely sub-classed
- e.g. list list = new arraylist();
- the new object not interesting 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: summary accurate, , make sense? there i've overlooked?
thanks in advance.
i'd don't use factory when have particular implementation want. continue list
example, know want arraylist
because i'm doing random access. don't want rely on factory getting right when can myself.
conversely, when don't want know concrete subclass can use factory , let worry object instantiate.
i guess i'd suggest add bullet "when use abstract factory pattern" says "and don't care concrete subclass get", , converse "when not use factory".
edit: careful avoid general-purpose tool-building factory factory factory.
Comments
Post a Comment