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:
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:
Explanation:
"Do I create a factory for every object type? That seems excessive."
When NOT to use a factory:
References:
My question is: is my summary accurate, and does it make sense? Is there anything I've overlooked?
Thanks in advance.
The Abstract Factory pattern helps you control the classes of objects that an application creates. Because a factory encapsulates the responsibility and the process of creating product objects, it isolates clients from implementation classes. Clients manipulate instances through their abstract interfaces.
The Abstract Factory design pattern solves problems like: How can an application be independent of how its objects are created?
Advantage of Abstract Factory Pattern Abstract Factory Pattern isolates the client code from concrete (implementation) classes. It eases the exchanging of object families. It promotes consistency among objects.
Java. The main difference between a “factory method” and an “abstract factory” is that the factory method is a single method, and an abstract factory is an object. The factory method is just a method, it can be overridden in a subclass, whereas the abstract factory is an object that has multiple factory methods on it.
I'd also say don't use a factory when you have a particular implementation that you want. To continue the List
example, I know that I want an ArrayList
because I'm doing random access. I don't want to rely on a factory getting this right when I can do it myself.
Conversely, when I don't want to know about the concrete subclass then I can use a factory and let it worry about which object to actually instantiate.
I guess I'd suggest that you add a bullet to the "when to use the abstract factory pattern" that says "and you don't really care which concrete subclass you get", and the converse to "when not to use a factory".
EDIT: Be careful to avoid the general-purpose tool-building factory factory factory.
In general, use it when you want to be able to switch of implementation by external configuration.
JDBC and JAXP are excellent examples. For more examples, check this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With