Skip to content

Instantly share code, notes, and snippets.

@scriptpapi
Created May 25, 2018 23:20
Show Gist options
  • Save scriptpapi/693f3c3a2911e89e2e1b781d5de037a9 to your computer and use it in GitHub Desktop.
Save scriptpapi/693f3c3a2911e89e2e1b781d5de037a9 to your computer and use it in GitHub Desktop.
A Template for implementing factory method in C++
// A Template for implementing factory method
#include <iostream>
using namespace std;
// Declare the available types that can be passed to the factory
enum robotType {R_Bipedal, R_Drone, R_Rover};
// Superclass
class Robot{
public:
virtual void printRobot() = 0;
static Robot* factory(robotType type);
};
// Sub-classes
class Bipedal: public Robot{
public:
void printRobot(){ cout << "I am a robot that walks" << endl; }
};
class Drone: public Robot{
public:
void printRobot(){ cout << "I am a robot that can fly" << endl; }
};
class Rover: public Robot{
public:
void printRobot(){ cout << "I am a rover like the one on mars" << endl; }
};
// This is the factory method
Robot* Robot::factory(robotType type) {
if(type == R_Bipedal)
return new Bipedal();
else if(type == R_Drone)
return new Drone();
else if(type == R_Rover)
return new Rover();
else
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment