This is useful when selecting drivers, sensors, or communication modules at runtime.
- Decouples creation from usage
- Supports runtime selection
C Example (Factory function)
Using pointer to function
#include <stdio.h>
#include <string.h>
typedef struct {
void (*draw)();
} Shape;
void drawCircle() { printf("Circle\n"); }
void drawSquare() { printf("Square\n"); }
Shape createShape(const char* type) {
Shape s;
if (strcmp(type, "circle") == 0)
s.draw = drawCircle;
else
s.draw = drawSquare;
return s;
}
int main() {
Shape s = createShape("circle");
s.draw();
}
C++ Example
Using function override
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() = 0;
};
class Circle : public Shape {
public:
void draw() override { cout << "Circle\n"; }
};
class Square : public Shape {
public:
void draw() override { cout << "Square\n"; }
};
class ShapeFactory {
public:
static Shape* create(const string& type) {
if (type == "circle") return new Circle();
if (type == "square") return new Square();
return nullptr;
}
};
int main() {
Shape* s = ShapeFactory::create("square");
s->draw();
delete s;
}