Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating object based on string parsed in

Suppose I have a class Image. At some point in parsing, "Image" is read in at the appropriate time, meaning I want to create an object of class Image.

What I'm considering is mapping these strings to a constructor call to the appropriate class, but I'm not sure how to accomplish this.

I.e.

container.push_back( some_map[stringParsedIn] ); // basic idea
like image 277
person Avatar asked Feb 25 '26 04:02

person


1 Answers

As Stephen pointed out, what you are describing is the Factory pattern (assuming that Image is an abstract base class). However, for its implementation, it might be helpful to associate strings with creation functions as you described instead of a large function consisting of if/else statements. Here's one way to do it (assuming your image subclasses can all be constructed the same way):

typedef Image* create_image_function();

template <class T>
Image* create_image(SomeType arg)
{
    return new T(arg);
}

...
map<string, create_image_function*> creators;
creators["Foo"] = &create_image<Foo>;
creators["Bar"] = &create_image<Bar>;
creators["Baz"] = &create_image<Baz>;

shared_ptr<Image> ImageFactory::make_image(const string& str)
{
    // checking to see if str exists as a key 
    // would be nice
    return shared_ptr<Image>(creators[str](arg));
}
like image 114
stinky472 Avatar answered Feb 26 '26 18:02

stinky472