开发者

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.


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.


Its a little hard to work out what you're intending with this, but you might want to consider an Abstract Factory pattern if you want to create a bunch of different subclasses based on some input parameter.


another way is to create an array where you will put pointers to the functions that will call corresponding constructor. And in your depends() you only will call the function that you need by given input. But any way you need 26 functions in this approach


The integer parameter "input" comes from somewhere. You might be able to let the code that created that int create the actual object instead. That won't work if you are reading the int from disk or something like that.

You might consider setting up a situation where the different subclasses register themselves with the object that creates them. In that case the factory object wouldn't need to know about the subclasses at compile time. You can have this done at start-up time using global variables whose constructors do the registering for each subclass. Your switch statement is simpler and faster, but it does mean you have to keep the switch up to date as you change the subclasses. It's a trade off and I don't think your solution is necessarily inferior to a more elaborate one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜