Factory pattern for classes

lexxn aleksandar.m.nikolov at gmail.com
Sun Aug 9 14:27:22 UTC 2020


On Sunday, 9 August 2020 at 12:24:05 UTC, Steven Schveighoffer 
wrote:
> 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

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. 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.



More information about the Digitalmars-d-learn mailing list