DEV Community

Discussion on: Explain Factory Pattern Like I'm Five

Collapse
 
johndougherty68 profile image
John Dougherty • Edited

You work as a salesperson where you travel around a lot. You use this nifty app on your laptop which can connect to the internet and get the latest info for your customer. This lets you be really up to date when you go to their office.

(Pretend this is how things are still done. The explanation works better this way :)

But maybe your internet connection is spotty in places and your program can't always get the very latest information because sometimes there's no internet. To make up for this, whenever it CAN connect it saves a copy of the latest info for your customers to your laptop. Later, if there's no internet connection the program can at least use this file so you're not completely blind.

So, your program has two different libraries for getting customer data: one it uses when there's an internet connection, and one is uses when there isn't and it has to use that file it saved from last time. But the libraries are written so that they've got all the same functions/methods. GetCustomerOrders, GetCustomerHistory, etc. are in both libraries, it's just that one goes to the internet and the other goes to the file on disk.

The "factory" part of this is that whenever your program starts up, it asks a special object to get it the library which gets access to the customer info. This "factory" object might have a single method: GetCustomerLibrary() or something. Depending on the internet connection, it hands back the connected version or the non-connected version of the customer information library.
But your program doesn't know the difference. It doesn't care. The two version of the library both do all the stuff you need.

As a side benefit, this pattern can be really useful in the early stages of app development. Maybe your app is going to access a database, but the database hasn't been completely built yet. Does this mean you have to wait until it is built?
No! Just have a version of your library which accesses a small file of dummy data, or an Excel spreadsheet, or something. As long as it has the same methods as the version which will use the database, you can develop with the file/Excel-based version until the database is online.