final str = Default.get<Baz>().baz();
print(str);
}
class Baz extends Foo {
String baz() => 'baz';
}
class Default {
static Map<Type, Function()> _ctors = {};
static void add<T>(T Function() ctor) {
if (_ctors.containsKey(T)) {
throw ArgumentError.value(ctor, 'ctor', 'Duplicate value');
}
_ctors[T] = ctor;
}
static T get<T>() => getByType(T);
static T getByType<T>(Type type) {
final ctor = _ctors[type];
if (ctor == null) {
throw ArgumentError.value(type, 'type', 'Constructor not found');
}
return ctor() as T;
}
}
abstract class Foo {
foo() {
final value = Default.getByType(runtimeType);
print(value.runtimeType);
}
}