Abstract Factory Pattern

Abstract Factory Pattern is one of the creational design pattern.

According to Gang Of Four intent of Abstract Factory Pattern is to Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

SAMPLE CODE:

#include <iostream>

using namespace std;

enum DBType { MYSQL, ORACLE, REDIS, MANGODB };

class Database {
public:
    virtual void read() = 0;
    virtual void write() = 0;
};

class MysqlDB : public Database {
    void read() {
        cout << "Read data from MYSQL RDBMS Database" << endl;
    }
    void write() {
        cout << "Write data to MYSQL RDBMS Database" << endl;
    }
};

class OracleDB : public Database {
    void read() {
        cout << "Read data from ORACLE RDBMS Database" << endl;
    }
    void write() {
        cout << "Write data to ORACLE RDBMS Database" << endl;
    }
};

class RedisDB : public Database {
    void read() {
        cout << "Read data from REDIS NOSQL Database" << endl;
    }
    void write() {
        cout << "Write data to REDIS NOSQL Database" << endl;
    }
};

class MangoDB : public Database {
    void read() {
        cout << "Read data from MANGODB NOSQL Database" << endl;
    }
    void write() {
        cout << "Write data to MANGODB NOSQL Database" << endl;
    }
};

class DataBaseFactory {
public:
    virtual Database * getDatabase(DBType choice) = 0;
};

class RDBMSFactory : public DataBaseFactory {
    Database * getDatabase(DBType choice) {
        Database * DBObject;
        if (choice == MYSQL) {
            DBObject = new MysqlDB();
        }
        else if (choice == ORACLE) {
            DBObject = new OracleDB();
        }
        else {
            DBObject = NULL;
        }
        return DBObject;
    }
};

class NOSQLFactory : public DataBaseFactory {
    Database * getDatabase(DBType choice) {
        Database * DBObject;
        if (choice == REDIS) {
            DBObject = new RedisDB();
        }
        else if (choice == MANGODB) {
            DBObject = new MangoDB();
        }
        else {
            DBObject = NULL;
        }
        return DBObject;
    }
};

int main()
{
    DataBaseFactory * rdbmsObject, * nosqlObject;
    Database * databaseObject;

    rdbmsObject = new RDBMSFactory();
    databaseObject = rdbmsObject->getDatabase(ORACLE);
    databaseObject->read();
    databaseObject->write();
    cout << "-----------------------------------------" << endl;
    nosqlObject = new NOSQLFactory();
    databaseObject = nosqlObject->getDatabase(REDIS);
    databaseObject->read();
    databaseObject->write();

    return 0;
}


OUTPUT:

Read data from ORACLE RDBMS Database
Write data to ORACLE RDBMS Database
-----------------------------------------
Read data from REDIS NOSQL Database
Write data to REDIS NOSQL Database


No comments:

Post a Comment