Skip to content

Instantly share code, notes, and snippets.

@FONQRI
Created December 30, 2017 11:43
Show Gist options
  • Save FONQRI/2ad568a68a7f7c935e64a6101fe35e9e to your computer and use it in GitHub Desktop.
Save FONQRI/2ad568a68a7f7c935e64a6101fe35e9e to your computer and use it in GitHub Desktop.
Static Factory Design Pattern
#include <iostream>
#include <string>
using namespace std;
// Abstract Base Class
class Shape {
public:
virtual void Draw() = 0;
virtual ~Shape();
// Static class to create objects
// Change is required only in this function to create a new object type
static Shape *Create(string type);
};
class Circle : public Shape {
public:
~Circle();
void Draw() { cout << "I am circle" << endl; }
friend class Shape;
};
Circle::~Circle() {}
class Square : public Shape {
public:
~Square();
void Draw() { cout << "I am square" << endl; }
friend class Shape;
};
Square::~Square() {}
Shape *Shape::Create(string type)
{
if (type == "circle")
return new Circle();
if (type == "square")
return new Square();
return NULL;
}
int main()
{
// Give me a circle
Shape *obj1 = Shape::Create("circle");
// Give me a square
Shape *obj2 = Shape::Create("square");
obj1->Draw();
obj2->Draw();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment