1、首先我们使用 typedef 来定义可以指向函数的指针类型 NewObject
typedef _class * (*NewObject)();
2、创建一个类(本身有一个newClass的静态函数)
class _class{
public:
static _class * newClass(){
return new _class ();
}
};
3、创建一个单例类
class ObjectManagement
{
public:
ObjectManagement(const ObjectManagement&) = delete;
ObjectManagement(ObjectManagement&&) = delete;
static ObjectManagement& instance(){
static ObjectManagement _instance;
return _instance;
}
void registerWidget(QString key,NewObject newObject){
objects.insert(key,newObject);
}
_class* newObject(QString key){
return objects.value(key)();
}
bool isContains(QString key){
return objects.contains(key);
}
private:
ObjectManagement(){}
QMap<QString,NewObject> objects;
};
4、注册
ObjectManagement * objectManagement= &ObjectManagement::instance();
objectManagement->registerWidget("_class",&_class::newClass);
5、使用
ObjectManagement* objectManagement= &ObjectManagement::instance();
auto _object = objectManagement->newObject("_class");
如果哪里有错误的话请指出。
如果对你有帮助可以点赞+评论+关注,您的支持是我产出更多更好内容的动力,谢谢。