基于解析的字符串创建对象 [英] Creating object based on string parsed in
问题描述
假设我有一个类 Image
。在解析的某个时刻,在适当的时间读入Image,这意味着我想创建一个 Image
类的对象。
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.
即
container.push_back( some_map[stringParsedIn] ); // basic idea
推荐答案
As Stephen指出,正在描述的是Factory模式(假设Image是一个抽象基类)。然而,对于它的实现,将字符串与创建函数相关联可能有所帮助,而不是由if / else语句组成的大函数。这里有一种方法(假设你的图像子类可以用相同的方法构造):
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));
}
这篇关于基于解析的字符串创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!