工厂模式,根据ID创建对应的实例类
//
// main.cpp
// TestCPP1
//
// Created by bianchx on 15/4/27.
// Copyright (c) 2015年 bianchx. All rights reserved.
// #include <iostream>
#include <map> class BaseClass
{
public:
virtual void print()
{
std::cout << __FUNCTION__ << std::endl;
}
}; typedef BaseClass *(*CreateBase)(); static std::map<long, CreateBase> _map; class Factory
{
public: static BaseClass *createInstanse(long id)
{
return _map.find(id)->second();
}
}; template <typename T>
struct ClassRegister:BaseClass {
ClassRegister(long _id)
{
_map[_id] = &(ClassRegister::createT);
} static BaseClass* createT()
{
return new T();
}
}; class ClassA:public BaseClass
{
public:
static ClassRegister<ClassA> reg; virtual void print()
{
std::cout << "ClassA" << std::endl;
}
}; ClassRegister<ClassA> ClassA::reg(1); class ClassB:public BaseClass
{
private:
static ClassRegister<ClassB> reg;
public:
virtual void print()
{
std::cout << "ClassB" << std::endl;
}
}; ClassRegister<ClassB> ClassB::reg(2); int main(int argc, const char * argv[]) { Factory::createInstanse(1)->print();
Factory::createInstanse(2)->print(); return 0;
}