Factory pattern for classes

Ali Çehreli acehreli at yahoo.com
Sun Aug 9 15:56:31 UTC 2020


On 8/9/20 7:27 AM, lexxn wrote:

 > I assume that the correct syntax for the getClassById is
 > Object getClassById(uint id) {
 >      if (id == 0) {
 >          return new A();
 >      } else if (id == 1) {
 >          return new B();
 >      } else {
 >          return new C();
 >      }
 > }
 > or maybe I'm wrong.

Because those example classes are not a part of a hierarchy, their 
common interface is Object. That is the only way to get the code compile.

 > This way if I try auto myClass = getClassById(0) and
 > if I've a method in A,B&C classes when I try to call it with myClass I
 > get no property methodName for type object.Object.

If methodName() is a virtual function of your hierarchy, then normally 
it is a part of an interface that all those classes implement and the 
return type is that common ancestor. Here is a working example:

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



More information about the Digitalmars-d-learn mailing list