我需要一種方法來實例化基於它的類名傳遞的對象爲std :: string。這是工作的權利,但需要加以概括:字符串名稱的C++通用對象工廠
void* create(std::string name) {
if(name == "classOne") return new ClassOne();
else if(name == "classTwo") return new ClassTwo();
/* ... */
}
什麼我沒有:
- 控制的類實例化:可以滿三十歲派對類。這個類沒有變化(即基礎祖先,多態創造者方法等)。
- 完整的類名列表:更多的類可以稍後添加,並且不應該改變這個工廠。
- 圍繞要實例化的類的包裝器:作爲前兩點的結果。
其他任何事情都是一回事。
最好使用情況將是:
int main() {
void *obj = create("classTree"); // create object based on the string name
/* ... */
// once we know by context which specific class we are dealing with
ClassTree *ct = (ClassTree*)obj; // cast to appropiate class
std::cout << ct->getSomeText() << std::endl; // use object
}
作爲一個方面,也許不相干的音符,您考慮被實例化可能來自一個類或結構的對象。
添加的信息
我看到的是需要更多的上下文。這裏是我的具體使用情況,簡化爲:
// registration mechanism
int main() {
std::map< std::string, void(*func)(std::string, void*) > processors; // map of processors by class name
processors["ClassFour"] = (void(*)(std::string, void*)) &classFourMessageProcessor; // register processor (cast needed from specific to generic)
}
// function receiving string messages
void externalMessageHandler(std::string msg) {
std::string objType = extractTypeFromMessageHeader(msg); // extract type from message
// now that we know what we are dealing with, create the specific object
void *obj = create(objType); // << creator needed
processors[objType](msg, obj); // dispatch message to process
}
// previously registered message processor
void classFourMessageProcessor(std::String msg, ClassFour *obj) {
std::string streetAddress = msg.substr(10, 15); // knowing the kind of message we can extract information
obj->moveTheEtherTo(streetAddress); // use the created object
}
添加的信息
我使用C++ 11的最新的GNU編譯器。
不僅僅是在我們知道我們正在處理的具體類是什麼時才實例化正確的類,然後做那些你會用這個'void *'做的事情? – Kal
@Kal在知道它是什麼類之前,您可能需要使用'obj'。 – SirGuy
這不是創建工廠的正常方式。由於大的if語句塊,它不會很好地擴展。請參閱http://stackoverflow.com/questions/5120768/how-to-implement-the-factory-pattern-in-c-correctly – Bathsheba