Context
Factory pattern is a creational design pattern. It allows users to instantiate specifics classes via Factory class. It also provides flexibility and extensibility. Developers can add new classes (features, products, etc) to the class, without distrupting existing classes.
From my experience, it has been particularly useful in working with analytical libraries. Below is a practical example.
Example
Suppose we have implemented a root finding algorithm - say Newton-Raphson method.
|
|
We also got another root finding algorithm developed by another team - let’s say bisection method.
|
|
If both algorithms are developed by the same team, we can just write an interface - something like GenericRootFinder and expose them to users.
However, we have 2 different methods from 2 different teams. In order to expose these in an organized way, we can throw in Factory pattern. This would allow both teams to focus on their methods, ship the analytical library in an unified manner, do maintenance with ease and introduce minimal breaks among users and their applications in the future.
So the Factory would look like this
|
|
Summary
Above Factory class can be extended in many ways without affecting existing implementations. It can bring in new algorithms of root finding. From client side, it could be as easy as changing a config to generate a different root-finding method instance.
In this article, I have shared what factory pattern is and its practical use case in organizing an analytical library.
If you have comments on this, you can reach me at hello@kaung.dev.
You can see the full implementation and tests at my github.
References
- My Practical Experience
- Gangs of Four - Design Patterns
- Factory Design Pattern in Java