Factory Pattern
In short, the Factory Pattern is a design pattern used to create classes or structures. It centralizes the creation rules to a single place in your code.
Use
I use the Factory Pattern in three situations.
Enable Substitution
Let’s say I’m building an eCommerce website and I want to allow my customers to select different payment options, like Credit Card, BitCoin, Apple Pay, or PayPal. After the user selects the option, enters some information, and submits, the application will process the order and payment. At that time, the code will create the chosen payment gateway, this is where the Factory Pattern comes in handy. The code will ask the factory to create a Payment Gateway object, typically defined as an abstract class or interface, from the option. If the option Credit Card the factory will return a Credit Card Payment Gateway object. By using an abstract class or interface for the Payment Gateway, we can substitute any implementation.
Hide Creation Rules
In the example earlier, the factory is hiding the rules for creating a Payment Gateway. It’s very simple, it creates an object based on a single variable, the selected payment type. Business rules aren’t always so simple. As applications evolve, business rules grow. Instead of maintaining multiple copies of an object’s creation it’s helpful to centralize to a single place, such as a factory. Even if you need multiple functions to create the same object, all the rules will live one class. Lastly, centralizing the rules also makes it very testable.
Testing
Once you’ve centralized the rules you can write unit tests specifically for the creation process. Additionally, Factories make testing other parts of the application stronger because you mock or stub the creation logic out and refocus the test.
Related Posts
December 9, 2015
Setup a Raspberry Pi Without a Monitor, Keyboard, or Mouse
October 27, 2014
OAuth 2 Flows
March 3, 2014
WordPress Theme Tips
February 5, 2014
Creating a TeamCity Project
February 15, 2013
Using Trello
September 6, 2012
UpshotHelper Update
July 26, 2012
UpshotHelper
May 5, 2012