Skip to content

Instantly share code, notes, and snippets.

@RDCH106
Last active March 14, 2017 15:24
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 RDCH106/a8bc98d6a57b4caa15eaf1af4b59f2a4 to your computer and use it in GitHub Desktop.
Save RDCH106/a8bc98d6a57b4caa15eaf1af4b59f2a4 to your computer and use it in GitHub Desktop.
In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method.
#include <iostream>
#include <memory>
#include <string>
struct Base
{
virtual ~Base() = default;
};
struct Derived : public Base
{
explicit Derived(int value) : value_(value) {}
~Derived() = default;
int value_;
};
struct Other : public Base
{
explicit Other(const std::string &foo, int bar = 3) : foo_(foo), bar_(bar) {}
~Other() = default;
std::string foo_;
int bar_;
};
struct Bar : public Base
{
Bar(int a, int b) : a_(a), b_(b) {}
~Bar() = default;
int a_;
int b_;
};
/* The magic is here */
namespace Factory
{
template <typename T, typename... Args>
std::unique_ptr<T> CreateStuff(Args... args)
{
return std::make_unique<T>(args...);
}
}
int main(int argc, char *argv[])
{
auto ptr = Factory::CreateStuff<Derived>(5);
if (!ptr) throw std::bad_alloc();
std::cout << "Derived: value: " << ptr->value_ << std::endl;
auto ptr2 = Factory::CreateStuff<Other>(std::string("foo"));
if (!ptr2) throw std::bad_alloc();
std::cout << "Other: string: " << ptr2->foo_ << " bar: " << ptr2->bar_ << std::endl;
auto ptr3 = Factory::CreateStuff<Bar>(5, 7);
if (!ptr3) throw std::bad_alloc();
std::cout << "Bar: a: " << ptr3->a_ << " b: " << ptr3->b_ << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment