Skip to content

Files

Latest commit

author
Jonathan DANIEL (contractor)
Sep 26, 2018
ab54c01 · Sep 26, 2018

History

History

FactoryPattern

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Jul 16, 2018
Sep 26, 2018
Jul 16, 2018
Jul 16, 2018
Sep 26, 2018
Jul 22, 2018

Factory Pattern

This is a factory pattern written in just a few lines of code.

template <class ReturnType, class ...Args>
using Factory = std::function<ReturnType(Args...)>;

Basically a Factory is a std::function that has a target callable that's based on parameters/arguments you define. This target callable will return an object of type ReturnType defined for the Factory.

An example of how to create a factory for a vector of N Animals:

/**
 * This factory type must return a vector of Animal objects.
 */
using FarmFactory = factory::Factory<std::vector<Animal>>;

FarmFactory farmFactory(int N)
{
	return [=]
	{
		std::vector<Animal> ret;
		for (std::size_t i = 0; i < N; i++)
			ret.push_back(Animal());

		return ret;
	};
}

// Create a farm with 20 animals
auto mediumFarmFactory = animalfactory::farmFactory(20); // Set the target based on parameters.
auto animals = mediumFarmFactory(); // Call the target of the std::function

Sequence Diagram

alternative text