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
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));
}
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