Factory pattern in D
Chris via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri May 1 04:20:31 PDT 2015
On Friday, 1 May 2015 at 11:11:28 UTC, biozic wrote:
> On Friday, 1 May 2015 at 11:01:29 UTC, Chris wrote:
>>
>> Thinking about it,
>>
>> T factory(T)() {
>> return T();
>> }
>>
>> is better suited for a factory (with static type checks).
>
> But then I don't know what factory!X() provides that X() alone
> doesn't.
Just cleaner code with type checks
T factory(T)() {
static if (is (T == A)
|| (is (T == B)))
return T();
else
assert(0, "Type "~T.stringof~" is not supported");
}
and then you could have
auto getType(string type = "")() {
static if (type == "A")
return factory!A();
else static if (type == "B")
return factroy!B();
else
return factory!A(); // default
}
in order to separate the logic, i.e. the factory produces the
type and performs all the type checks, whereas `getType` is the
interface for the user.
>> This aside, how would I get something to load dynamically?
>> It's either "mismatched function return type" or (with type
>> check) "variable X cannot be read at compile time":
>>
>> void main(string[] args) {
>> auto type = args[1];
>> auto myType = factory!type();
>> }
>>
>> So it's back to classes/interfaces again? Hmmmm.
>
> Indeed. Runtime polymorphism is based on classes and
> interfaces. The struct and template solutions can only make
> "compile-time factories".
Yep. Only that "compile-time factories" kinda defeat the purpose.
More information about the Digitalmars-d-learn
mailing list