Factory pattern for classes

Martin martin.brzenska at googlemail.com
Mon Aug 10 18:54:02 UTC 2020


On Sunday, 9 August 2020 at 15:56:31 UTC, Ali Çehreli wrote:
> module deneme;
>
> import std.stdio;
>
> interface I {
>   void methodName();
> }
> ...
> I getClassById(uint id)
> {
>     if (id == 0) {
>         return cast(A)Object.factory("deneme.A");
>     } else if(id == 1) {
>         return cast(B)Object.factory("deneme.B");
>     } else {
>         return cast(C)Object.factory("deneme.C");
>     }
> }
>
> void main() {
>   auto o = getClassById(1);
>   o.methodName();
> }

Why not simply do?
>I getClassById(uint id)
>{
>    if (id == 0) {
>        return new A();
>    } else if(id == 1) {
>        return new B();
>    } else {
>        return new C();
>    }
>}

Then you can also pass parameters to the constructors or call 
further factories to create them, as long as they return a 
`I`-compatible type.


More information about the Digitalmars-d-learn mailing list