Factory Design Pattern

Concepts

Factory Design Pattern simplifies the process to create object types by creating interface Factory and delegate the creation to subclasses. Based on the input from client, different object types could be returned.

// the interface 
Product * IFactory::create(int, int , int) = 0;

// the concrete class would specificly implements the creation of object type based on input
Product * Car::create(int model, int type, int class){
        return Product newCar = new Car(model, type, class);  // Car is a subclass of Product
}

Implementation

  • At the core of the design patterns are 2 interfaces, IFactory that generalizes how an object type should be created (and other operations that may be needed) and IProduct that generalized the object types
  • We have concrete classes such as CarShip, that implements both IFactory and IProduct
#include <iostream>
#include <vector>

class IProduct{
    virtual void run()=0;
    virtual void build()=0;
};

class Car : public IProduct{
    public:
    Car (int model, int type) : model_(model) , type_(type) {} ;
    virtual void build() override {
       // implement car run logic
       std::cout<<"car is building"<<std::endl;
    };
    virtual void run() override {
       // implement car run logic
       std::cout<<"car is running"<<std::endl;
    };

    private:
    int model_;
    int type_;
};

class Ship : public IProduct{
    public:
    Ship (int model, int type) : model_(model) , type_(type) {} ;
    virtual void build() override {
        // implement ship run logic
        std::cout<<"ship is building"<<std::endl;
    };
    virtual void run() override {
       // implement ship drive logic
       std::cout<<"car is running"<<std::endl;
    };
    private:
    int model_;
    int type_;
};

class IFactory{
    public:
    virtual IProduct * create() = 0;
};

class CarAssembly : public IFactory {
    public:
    virtual Car * create() override {
        car_ = new Car(1,1);
        return car_;
    }
    private:
    Car * car_;
};

class ShipAssembly : public IFactory {
    public:
    virtual Ship* create() override {
        ship_ = new Ship(1,1);
        return ship_;
    }
    private:
    Ship * ship_;
};

int main(){

    CarAssembly * carAssembly = new CarAssembly;
    Car * car = carAssembly->create();
    car->build();
    car->run();
};

Analysis: Benefits of Factory Pattern

Mr.Stephen from StackExchange explains the benefit of Factory design:

  • It allows you to introduce an Inversion of Control (IoC) container easily
  • It allows Encapsulation and Abstraction.
  • It makes your code more testable as you can mock interfaces
  • Code reusability and Code scalability: It gives you a lot more flexibility when it comes time to change the application (i.e. you can create new implementations without changing the dependent code)

Leave a Reply

Your email address will not be published. Required fields are marked *