一、目的1 通过复制这些原型对象创建新对象。2当实例化的类是在运行是指定时就可以通过这种方式#includeiostream #includestring #includeunordered_map using namespace std; class Something{ public: Something(int id,string type):m_id(id),m_type(type){coutSomething构造函数被调用endl;} virtual ~Something(){coutSomething析构函数调用endl;} virtual Something* clone()0; virtual string who()0; virtual int typeId()0; Something(const Something something){ this-m_id something.m_id; this-m_typesomething.m_type; coutSomething拷贝构造调用endl; } protected: int m_id; string m_type; }; class Human:public Something{ public: Human(int id,string type):Something(id,type){coutHuman构造数被调用endl;} Human(const Human human):Something(human){coutHuman拷贝构造函数调用endl;} virtual Something* clone() override {return new Human(*this);} virtual string who() override {return m_type;} virtual int typeId() override{return m_id;} ~Human(){coutHuman析构函数被调用endl;} }; class Dog:public Something{ public: Dog(int id,string type):Something(id,type){coutdog构造函数被调用endl;} Dog(const Dog dog):Something(dog){coutdog拷贝构造函数被调用endl;} ~Dog(){coutDog析构被调用endl;} virtual string who() override {return m_type;} virtual int typeId() override{return m_id;} virtual Something* clone() override {return new Dog(*this);} }; class All{ public: ~All(){ //析构函数 for (auto x : m_SomeMap) { delete x.second; x.second nullptr; } } All() //构造函数 { Human* human new Human{1, 人类 }; Dog* dog new Dog{2,狗类}; m_SomeMap.emplace(human-who(), human); m_SomeMap.emplace(dog-who(), dog); } //根据你所需要的种类来获得克隆对象 Something* getSome(string Type){return m_SomeMap[Type]-clone();} private: unordered_mapstring, Something* m_SomeMap; }; int main(int agv,char* agc[]){ cout 开始测试endl; All factory; // 克隆人类 Something* p1 factory.getSome(人类); cout 克隆类型 p1-who() id: p1-typeId() endl; delete p1; // 克隆狗 Something* p2 factory.getSome(狗类); cout 克隆类型 p2-who() id: p2-typeId() endl; delete p2; // 测试不存在类型 //Something* p3 factory.getSome(猫类); return 0; }二、运行结果kickpikickpi:~/test$ g prototype.cpp -o main2 kickpikickpi:~/test$ ./main2 开始测试 Something构造函数被调用 Human构造数被调用 Something构造函数被调用 dog构造函数被调用 Something拷贝构造调用 Human拷贝构造函数调用 克隆类型人类 id:1 Human析构函数被调用 Something析构函数调用 Something拷贝构造调用 dog拷贝构造函数被调用 克隆类型狗类 id:2 Dog析构被调用 Something析构函数调用 Dog析构被调用 Something析构函数调用 Human析构函数被调用 Something析构函数调用