Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giant switch statement for constructors

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.

like image 839
Seth Carnegie Avatar asked Jul 16 '11 05:07

Seth Carnegie


Video Answer


1 Answers

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.

like image 119
Alok Save Avatar answered Sep 29 '22 23:09

Alok Save