Factory Design Pattern
This pattern falls into the Creational pattern type and this is used when we need to create instances but without disclosing or revealing the creation logic. Simply encapsulating the object creation. This method implements an abstract class or an interface to create an object but the object creation is decided by the subclasses (like which class to instantiate). This pattern is also known as the “ Virtual Constructor”.
This pattern is completely different from the singleton patterns since this takes arguments to instantiate classes and creates multiple instances.
let's take a look at a real-world example; Think there is a system that uses multiple databases such as oracle, mssql and mongo and the system decide to connect with the database based on the client request. If the client wants to connect to the oracle DB client pass an argument as oracle then it creates a driver instance to connect with the DB, and the same happens with the other DBs.
Get Kalana Ravishan Uduwarage’s stories in your inbox
Join Medium for free to get updates from this writer.
Code:-
In here what happens is we take object creation to the DBFactory and create instances according to the passed parameters then it decides what class should be instantiated and deploys the required instance.
Think if we need to update the driver or make changes, we can perform that simply by changing the relevant parts of the DBfactory method despite changing all the codes from the client-side. Through this design pattern, we can achieve the decouplinge of the client's object creation.








