Logo

Programming-Idioms

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

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.

use Safe::Isa;
sub fact {
    my ($class, $str) = @_;
    return $class->new($str) if $class->$_isa('Parent');
}
#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);
}
auto fact(T, A...)(A a)
if (is(T==class) && is(T: Parent))
{
    return new T(a);
}
type ParentFactory func(string) Parent

var fact ParentFactory = func(str string) Parent {
	return Parent{
		name: str,
	}
}
class Parent {
    constructor(str) {}
    fact(new_class, str) {
        if (new_class.prototype instanceof Parent) {
            return new new_class(str)
        }
    }
}

class Child extends Parent {}
type Parent = class
  constructor create(const str: string);
end;

type ClassOfParent = class of Parent;

function fact(ClassType: ClassOfParent; const str: string): Parent;
begin
  result := ClassType.Create(str);
end;
def fact(a_class, str_):
    if issubclass(a_class, Parent):
        return a_class(str_)
def fact(klass, str)
  klass.new(str) if klass.is_a?(Parent)
end
use core::fmt::Debug;
use std::str::FromStr;
fn fact<Parent: std::str::FromStr>(str: String, _: Parent) -> Parent where <Parent as FromStr>::Err: Debug 
{
    return str.parse::<Parent>().unwrap();
}

New implementation...
< >
bbtemp