Factory Design Pattern

Factory is the most used and well know design pattern. Let me explain this to you with a small scenario I have. So when I was working on a backend application, I was suppose to interact with the database, but in order to make my backend application more flexible in database regards, I thought of writing code in such a way that is it easier to change between databases, for example, if today I am using MySQL and tomorrow I want to connect to MongoDB I would be doing it with ease.

interface DataBase{
    Query createQuery();
}
class userService{
    DataBase db;
    Query query = db.createQuery();
}

if you consider in the above class createQuery is the method returning a query object. That's a factory method. " Factory method is a method in the interface which returns an instance of another specific class ".

Here the Query object differs for every database I am using, so in order to maintain that isolation, there is a class for every query which returns the appropriate query object. Hence the createQuery method of Mysql class calls the MysqlQuery class's createQuery method and that gives us the actual MySQL query object.

This way there could be many factory methods in an interface, for example, Transaction createTransaction() or Execute execute(). This is when SRP is getting violated meaning the single responsibility of the Database interface is getting violated, now it has to get many corresponding objects.

That's when AbstractFactory comes into play. divide responsibility.

  1. Interface 1 has general Methods.

  2. Interface2 has only factory methods.

The Interface1 with no factory methods is called Database Interface, the interface with factory methods is called DatabaseFactory.

class userService{
    DataBase db;
    DataBaseFactory dbf;
}

There is another way of implementing the factory design pattern that is practical factory. here we can use a class to get the factory instance.

class DBFactoryService implements DataBaseFactory {
    DataBaseFactory getDataBaseFactory(String dbName){
        if(dbName="MYSQL"){
            return new MySqlFactory();
        }
        else if(dbName=="MongoDB"){
            return new MongoDBFactory();
        }
        else if(dbName=="PSql"){
            return new PSqlFactory();
        }
    }
}

This is pretty much about factory design pattern. Thanks for reading, happy learning bye.