Factory pattern for classes

Steven Schveighoffer schveiguy at gmail.com
Sun Aug 9 12:24:05 UTC 2020


On 8/9/20 5:16 AM, lexxn wrote:
> I'm trying to get the factory pattern going with classes
> class A {}
> 
> class B {}
> 
> class C {}
> 
> auto getClassById(uint id)
> {
>      if (id == 0) {
>          return cast(A)Object.factory("A");
>      } else if(id == 1) {
>          return cast(B)Object.factory("B");
>      } else {
>          return cast(C)Object.factory("C");
>      }
> }
> 
> I'm getting 2 errors:
> main.d(69): Error: Expected return type of main.A, not main.B:
> main.d(67):        Return type of main.Ainferred here.

Change your return type to Object.

> Also is it possible to completely skip the getClassById function and if 
> I've and array string classes = ["A", "B"] to just 
> cast(classes[0])Object.factory(classes[0]);. I understand that I need to 
> cast classes[0].

This won't work.

If you know what your class is going to be, I'd just import the file 
that contains it and avoid the whole Object.factory deal. It's going to 
go away anyways.

In other words:

Object getClassById(uint id)
{
     if (id == 0) {
         return new A;
     } else if(id == 1) {
         return new B;
     } else {
         return new C;
     }
}

-Steve


More information about the Digitalmars-d-learn mailing list