Factory Method


Description:

Intent

  • Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  • Defining a "virtual" constructor.
  • The new operator considered harmful.

Example:

Note

Idea:

Check list

  1. If you have an inheritance hierarchy that exercises polymorphism, consider adding a polymorphic creation capability by defining a static factory method in the base class.
  2. Design the arguments to the factory method. What qualities or characteristics are necessary and sufficient to identify the correct derived class to instantiate?
  3. Consider designing an internal "object pool" that will allow objects to be reused instead of created from scratch.
  4. Consider making all constructors private or protected.

Code:

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

class Computer{
public:
    virtual void run() = 0;
    virtual void stop() = 0;
    virtual ~Computer() {} // will call derived class destructor automatically
};

class Laptop: public Computer{
public:
    void run() override{
        cout<<"Laptop is running!\n";
        m_hibernate = false;
    }
    void stop() override{
        cout<<"Laptop is hibernating!\n";
        m_hibernate = true;
    }
private:
    bool m_hibernate;
};

class Desktop: public Computer{
public:
    void run() override{
        cout<<"Desktop is on!\n";
        m_on=true;
    }
    void stop() override{
        cout<<"Desktop is off!\n";
        m_on=false;
    }
private:
    bool m_on;
};

class ComputerFactory{
public:
    static Computer * newComputer(string computer_type){
        if(computer_type == "laptop") 
            return new Laptop;
        else if(computer_type == "desktop")
            return new Desktop;
        else
            return nullptr;
    }
};

int main(){
    Computer * computer1 = ComputerFactory::newComputer("laptop");
    Computer * computer2 = ComputerFactory::newComputer("desktop");

    computer1->run();
    computer1->stop();
    computer2->run();
    computer2->stop();
}

results matching ""

    No results matching ""