/* \file Test a less simple factory idiom. Factory can create several objects, which can be delivered on a first-in-first-out basis. The delivery takes place by assigning an Owned<T*> input argument to the next available Owned in the list of created objects. */ #include <list> #include "Deriveds.hh" #include "OwnedPtr.hh" using namespace MangoPtr; /* Simple factory class that can store many created objects. The objects are delivered in the order they were created (FIFO, first-in-first-out). */ class FactoryFIFO { std::list<Owned<Base*, OShared> > owners; public: void create(const std::string& type) { if (type=="derived1") { owners.push_back(); owners.back().takeOwnership(new Derived1); } else if (type=="derived2") { owners.push_back(); owners.back().takeOwnership(new Derived2); } else if (type=="derived3") { owners.push_back(); owners.back().takeOwnership(new Derived3); } else throw std::logic_error("Unknown type"); } void getObj( Owned<Base*, OShared>& newOwned ) { std::cout << "FactoryFIFO: giving object from list" << std::endl; Owned<Base*, OShared>& owner = owners.front(); if ( owner.isNull()) throw std::logic_error("No object created"); newOwned.takeOwnership( owner.giveOwnership() ); owners.erase(owners.begin()); } }; /* Get \a num objects form \a factoryFIFO. */ void getObjects(FactoryFIFO& factoryFIFO, int num) { std::cout << "Getting FIFO objects" << std::endl; Owned<Base*, OShared> mango; for (int i=0; i<num; i++) { factoryFIFO.getObj( mango ); mango()->callVirtual(); } } int main() { try { std::cout << "Using FactoryFIFO" << std::endl; FactoryFIFO factoryFIFO; // create five objects factoryFIFO.create("derived1"); factoryFIFO.create("derived2"); factoryFIFO.create("derived3"); factoryFIFO.create("derived2"); factoryFIFO.create("derived1"); // get only four objects getObjects(factoryFIFO, 4); std::cout << "Done FactoryFIFO use" << std::endl; } catch (const std::exception& e) { std::cout << e.what() << std::endl; } }