/* \file Test a simple factory idiom. Factory creates an object of a derived type of Base and delivers the object to the caller upon demand. */ #include "Deriveds.hh" #include "OwnedPtr.hh" using namespace MangoPtr; /* A simple factory class. */ class FactoryOne { Owned<Base*> owner; public: void create(const std::string& type) { if (type=="derived1") owner.takeOwnership(new Derived1); else if (type=="derived2") owner.takeOwnership(new Derived2); else throw std::logic_error("Unknown type"); } void getObj( Owned<Base*>& newOwned ) { std::cout << "FactoryOne: giving object" << std::endl; if (owner.isNull()) throw std::logic_error("No object created"); newOwned.takeOwnership( owner.giveOwnership() ); } }; /* Use factory to make object of given type, call method on it. */ void make(FactoryOne& factory, const std::string& type) { factory.create(type); Owned<Base*> mango; factory.getObj(mango); assert(mango.isNotNull()); mango()->callVirtual(); } int main() { try { std::cout << "Using FactoryOne" << std::endl; FactoryOne factory; make(factory, "derived1"); make(factory, "derived2"); } catch (const std::exception& e) { std::cout << e.what() << std::endl; } }