Created
October 17, 2014 14:58
-
-
Save SunRain/47728e2a73e9587c25e6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <map> | |
#include <string> | |
#include <iostream> | |
namespace MyNameSpace { | |
class Base | |
{ | |
public: | |
virtual char* GetName() const = 0; | |
}; | |
class FactoryBase | |
{ | |
public: | |
virtual Base *Create() = 0; | |
}; | |
static std::map<std::string, FactoryBase *> factoryMap; | |
#define CREATE_FACTORY(TypeName) \ | |
class Factory##TypeName : public FactoryBase \ | |
{ \ | |
public: \ | |
Factory##TypeName() \ | |
{ \ | |
factoryMap[#TypeName] = this;\ | |
} \ | |
virtual Base *Create() \ | |
{ \ | |
return new TypeName;\ | |
} \ | |
}__##TypeName; | |
class MainClass { | |
public: | |
void doSomething () { | |
FactoryBase *pFBase = factoryMap["B"]; | |
Base *pBase = pFBase->Create(); | |
std::cout << pBase->GetName() << std::endl; | |
} | |
public: | |
class A : public Base | |
{ | |
public: | |
virtual char *GetName() const | |
{ | |
return "A"; | |
} | |
}; | |
class B : public Base | |
{ | |
public: | |
virtual char *GetName() const | |
{ | |
return "B"; | |
} | |
}; | |
CREATE_FACTORY(A) | |
CREATE_FACTORY(B) | |
}; | |
} | |
int main() | |
{ | |
MyNameSpace::MainClass m; | |
m.doSomething(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment