Factory pattern for classes

lexxn aleksandar.m.nikolov at gmail.com
Sun Aug 9 20:47:27 UTC 2020


On Sunday, 9 August 2020 at 15:56:31 UTC, Ali Çehreli wrote:
> On 8/9/20 7:27 AM, lexxn wrote:
>
> module deneme;
>
> import std.stdio;
>
> interface I {
>   void methodName();
> }
>
> class A : I {
>   void methodName() {
>     writeln("A");
>   }
> }
>
> class B : I {
>   void methodName() {
>     writeln("B");
>   }
> }
>
> class C : I {
>   void methodName() {
>     writeln("C");
>   }
> }
>
> 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();
> }
>
> Ali

This is the solution I will use, at least for now. Thank you Ali.



More information about the Digitalmars-d-learn mailing list