-
-
Save benben/1051577 to your computer and use it in GitHub Desktop.
Object factory using Boost.Phoenix, Boost.Function and Boost.SmartPtr libraries
This file contains 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 <boost/foreach.hpp> | |
#include <boost/function.hpp> | |
#include <boost/spirit/include/phoenix.hpp> | |
#include <boost/shared_ptr.hpp> | |
#include <iostream> | |
#include <map> | |
#include <string> | |
#include <vector> | |
struct Parent { virtual std::string hello() const = 0; }; | |
struct Object1 : Parent { std::string hello() const { return "Hi, Object1"; } }; | |
struct Object2 : Parent { std::string hello() const { return "Ay, Object2"; } }; | |
struct bad_type_exception : std::exception { | |
char const * what() const throw() { return "No such class!"; } | |
}; | |
typedef boost::shared_ptr<Parent> ParentPtr; | |
struct Factory { | |
typedef std::map<std::string, boost::function<ParentPtr()> > FactoryMap; | |
FactoryMap f; | |
Factory() { | |
using boost::phoenix::new_; | |
using boost::phoenix::construct; | |
f["Object1"] = construct<ParentPtr>(new_<Object1>()); | |
f["Object2"] = construct<ParentPtr>(new_<Object2>()); | |
// ... | |
} | |
ParentPtr operator()(std::string const & type) const { | |
FactoryMap::const_iterator it = f.find(type); | |
if (it == f.end()) throw bad_type_exception(); | |
return it->second(); | |
} | |
}; | |
int main() { | |
Factory factory; | |
std::vector<std::string> types; | |
types.push_back("Object1"); | |
types.push_back("Object2"); | |
std::vector<ParentPtr> items; | |
BOOST_FOREACH(std::string const & type, types) | |
items.push_back(factory(type)); | |
BOOST_FOREACH(ParentPtr item, items) | |
std::cout << item->hello() << std::endl; | |
// Prints: | |
// Hi, Object1 | |
// Ay, Object2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment