Skip to content

Instantly share code, notes, and snippets.

@plusangel
Created June 6, 2020 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plusangel/4e4456208cb6c7c1e11d751a2f66ff8f to your computer and use it in GitHub Desktop.
Save plusangel/4e4456208cb6c7c1e11d751a2f66ff8f to your computer and use it in GitHub Desktop.
Simple factory pattern example
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>
int main() {
auto my_shape = ShapeFactory::CreateShape(Shapes::kTriangle);
std::cout << "the are of the shape is " << my_shape->GetArea() << std::endl;
return 0;
}
//
// Created by angelos on 06/06/2020.
//
#ifndef FACTORY_METHODS_RECTANGLE_H
#define FACTORY_METHODS_RECTANGLE_H
#include "shape.h"
class Rectangle : public Shape {
public:
int GetArea() override {
return (width_*height_);
}
};
#endif//FACTORY_METHODS_RECTANGLE_H
//
// 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; }
protected:
int width_ = 5;
int height_ = 5;
};
#endif//FACTORY_METHODS_SHAPE_CLASS_H
//
// Created by angelos on 06/06/2020.
//
#include "shape_factory.h"
#include "rectangle.h"
#include "triangle.h"
Shape* ShapeFactory::CreateShape(Shapes type) {
if (type == Shapes::kRectangle) {
return new Rectangle;
}
if (type == Shapes::kTriangle) {
return new Triangle;
}
}
//
// Created by angelos on 06/06/2020.
//
#ifndef FACTORY_METHODS_SHAPE_FACTORY_H
#define FACTORY_METHODS_SHAPE_FACTORY_H
#include "shape.h"
enum class Shapes { kRectangle,
kTriangle };
class ShapeFactory {
public:
static Shape *CreateShape(Shapes type);
};
#endif//FACTORY_METHODS_SHAPE_FACTORY_H
//
// Created by angelos on 06/06/2020.
//
#ifndef FACTORY_METHODS_TRIANGLE_H
#define FACTORY_METHODS_TRIANGLE_H
#include "shape.h"
class Triangle : public Shape {
public:
int GetArea() override {
return (width_*height_)/2;
}
};
#endif//FACTORY_METHODS_TRIANGLE_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment