Skip to content

Instantly share code, notes, and snippets.

@plusangel
Created June 13, 2020 18:02
Show Gist options
  • Save plusangel/0becc1f8b606faf60bd67b8ab5f3c33a to your computer and use it in GitHub Desktop.
Save plusangel/0becc1f8b606faf60bd67b8ab5f3c33a to your computer and use it in GitHub Desktop.
Extensible factory template
cmake_minimum_required(VERSION 3.16)
project(factory_methods)
set(CMAKE_CXX_STANDARD 17)
add_library(shape_factory shape_factory.cpp)
add_executable(factory_method main.cpp)
target_link_libraries(factory_method shape_factory)
#include "shape_factory.h"
#include <iostream>
class SquareShape : public Shape {
public:
int GetArea() override {
return width_ * height_;
}
~SquareShape() override = default;
static Shape *Create() { return new SquareShape; }
};
int main() {
//register a new Shape
ShapeFactory::RegisterShape("square", SquareShape::Create);
Shape *s = ShapeFactory::CreateShape("square");
std::cout << "the area of the shape is " << s->GetArea() << std::endl;
delete s;
return 0;
}
//
// Created by angelos on 06/06/2020.
//
#ifndef FACTORY_METHODS_SHAPE_CLASS_H
#define FACTORY_METHODS_SHAPE_CLASS_H
// interface
class Shape {
public:
virtual int GetArea() = 0;
void set_width(int width) { width_ = width; }
void set_height(int height) { height_ = height; }
virtual ~Shape() = default;
protected:
int width_ = 5;
int height_ = 5;
};
#endif//FACTORY_METHODS_SHAPE_CLASS_H
//
// Created by angelos on 06/06/2020.
//
#include "shape_factory.h"
CallbackMap ShapeFactory::shapes_;
void ShapeFactory::RegisterShape(std::string_view type, CreateCallback cb) {
shapes_[type] = cb;
}
void ShapeFactory::UnregisterShape(std::string_view type) {
shapes_.erase(type);
}
Shape* ShapeFactory::CreateShape(std::string_view type) {
CallbackMap::iterator it = shapes_.find(type);
if (it != shapes_.end()) {
//call the creation callback to constrict the derived type
return (it->second)();
}
return nullptr;
}
//
// Created by angelos on 06/06/2020.
//
#ifndef FACTORY_METHODS_SHAPE_FACTORY_H
#define FACTORY_METHODS_SHAPE_FACTORY_H
#include "shape.h"
#include <map>
#include <string_view>
using CreateCallback = Shape* (*)();
using CallbackMap = std::map<std::string_view , CreateCallback>;
class ShapeFactory {
public:
static void RegisterShape(std::string_view type, CreateCallback cb);
static void UnregisterShape(std::string_view type);
static Shape* CreateShape(std::string_view type);
private:
static CallbackMap shapes_;
};
#endif//FACTORY_METHODS_SHAPE_FACTORY_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment