Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #73 Create a factory

Create a factory named fact for any sub class of Parent and taking exactly one string str as constructor parameter.

type ParentFactory func(string) Parent

var fact ParentFactory = func(str string) Parent {
	return Parent{
		name: str,
	}
}

A Factory is a function which returns an object.

Go doesn't have subtyping, but Parent could be any type: struct, interface, etc.
#include <string>
#include <type_traits>
template <typename T,
          std::enable_if_t<
            std::is_base_of_v<Parent, T>, bool> = true>
T fact(const std::string& str) {
  return T(str);
}

New implementation...
< >
bbtemp