纯C++下实现通过字符串创建不同的自定义类对象
#include <iostream>
#include <map>
#include <string>
using namespace std;
// 定义基类
class Base {
public:
virtual void doSomething() = 0;
virtual ~Base() {}
};
// 定义派生类A
class A : public Base {
public:
void doSomething() {
cout << "This is A." << endl;
}
};
// 定义派生类B
class B : public Base {
public:
void doSomething() {
cout << "This is B." << endl;
}
};
// 定义工厂类
class Factory {
public:
// 注册类
static void registerClass(const string& name, Base* obj) {
classMap[name] = obj;
}
// 创建类
static Base* createClass(const string& name) {
if (classMap.find(name) != classMap.end()) {
return classMap[name];
}
return nullptr;
}
private:
static map<string, Base*> classMap;
};
map<string, Base*> Factory::classMap;
// 注册类到工厂
void registerClasses() {
Factory::registerClass("A", new A());
Factory::registerClass("B", new B());
}
int main() {
registerClasses();
// 通过字符串实例化类对象
string className = "A";
Base* obj = Factory::createClass(className);
if (obj != nullptr) {
obj->doSomething();
}
className = "B";
obj = Factory::createClass(className);
if (obj != nullptr) {
obj->doSomething();
}
return 0;
}
#include <iostream>
#include <string>
#include <map>
// 基类
class Base {
public:
virtual void print() = 0; // 纯虚函数
};
// 子类1
class Derived1 : public Base {
public:
void print() override {
std::cout << "Derived1" << std::endl;
}
};
// 子类2
class Derived2 : public Base {
public:
void print() override {
std::cout << "Derived2" << std::endl;
}
};
// 根据字符串创建对象
std::map<std::string, std::function<Base*()>> factory {
{"Derived1", []() -> Base* { return new Derived1; } },
{"Derived2", []() -> Base* { return new Derived2; } },
};
int main() {
std::string type = "Derived1"; // 这里我们使用字符串来决定创建哪种类型的对象
Base* obj = factory[type](); // 使用map中的函数创建对象
obj->print(); // 调用对象的print方法,输出"Derived1"
delete obj; // 不要忘记删除创建的对象!
return 0;
}