I have a container which holds a bunch of pointers to a base class, and a function which takes some input and returns a class which is a subclass of the base class. Which subclass it returns depends on the input.
Right now, I have a giant switch statement like this:
class Base { ... }
class A : public Base { ... }
class B : public Base { ... }
...
class Z : public Base { ... }
Base* depends(int input) {
switch (input) {
case 1:
return new A(...);
case 2:
return new B(...);
...
case 26:
return new Z(...);
default:
...
}
}
I was wondering if there's any better way to design this. I don't know many "design patterns" (I think that's what they're called) so I don't know if there's a (obvious) better way to design this.
What you are looking for is an Factory Method pattern.
The important thing here is to remove the need for the Base class to have any knowledge of the derived class implementations. It is a bad design for a Base class to have knowledge about Derived classes.
Factory Method pattern addresses the above problem as the creation occurs outside of the Base class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With