Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I am trying to use a map as a way to implement an object factory. In Python it is possible to store a class type in a map, and use it later to create objects from that type:

class Foo:
    # ...

class Bar:
    # ...

factory_map = { 'foo' : Foo, 'bar' : Bar }
foo_object = factory_map['foo']()

I am not aware of a similar feature (i.e., storing a type in a map) in C++, so I came up with a solution based on lambda functions where the map stores functions responsible to create the objects:

class Base {
public:
    typedef std::unique_ptr<Base> Pointer;
    virtual void hi() = 0;
};

class Foo : public Base {
public:
    void hi() { std::cout << "Hi, it's foo\n"; }
};

class Bar : public Base {
public:
    void hi() { std::cout << "Hi, it's bar\n"; }
};

int main() {
    std::map<
        std::string,
        std::function<Base::Pointer()>> factory_map = {
            { "foo", []() { return Base::Pointer(new Foo()); } },
            { "bar", []() { return Base::Pointer(new Bar()); } },
        };

    Base::Pointer b1 = factory_map["foo"]();
    b1->hi();

    Base::Pointer b2 = factory_map["bar"]();
    b2->hi();
}

This might be the most straightforward solution to obtain Python's simplicity. I am wondering, however, if the usage of lambdas is the best way to create the factory. Specifically, I would like to know what are the pros/cons of this approach compared to a more "traditional" factory design (i.e., one using if/else conditionals to decide the type of the object to create).

share|improve this question
I would not say if/else is more traditional. I would say that using a map was more traditional (were do you think python got that pattern from). – Loki Astari Aug 15 '12 at 17:26
@LokiAstari Well, in many places I have seen factories implemented with conditionals. One example could be the C++ example in Wikipedia. – betabandido Aug 15 '12 at 18:26
1  
Sure you can do it with conditionals just like you can in Python. Its an easy way to explain the concept this way. But in the real world you would use a map as you can add factory functions dynamically. Also I don't think wikipedia is not a great source for good examples. It is a good point to start research on a subject but follow the links to more authoritative pages (like SO). – Loki Astari Aug 15 '12 at 19:50
Maybe try something like this self-registering factory. – Kerrek SB Aug 17 '12 at 17:10

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.