///////////////////////////////////////////////// // MT2Q3.cpp - Factory for Singleton // // // // Jim Fawcett, CSE687 - Midterm, Spring 2010 // ///////////////////////////////////////////////// #include #include #include template // You need to use templates to build class factory // one factory to create many deriveds. { public: B* Create() // create singleton instance, useful for shared resource { if(instance != 0) return instance; return (instance = new D()); // this will succeed only if D derives } // from B or is B private: static D* instance; }; template D* factory::instance = 0; class Base { public: Base() { ++count; } virtual ~Base() {}; virtual std::string say() { return "\n Base here with count = " + instanceCount(); } std::string instanceCount() { std::ostringstream temp; temp << count; return temp.str(); } private: static size_t count; }; size_t Base::count = 0; class Derived1 : public Base { public: virtual std::string say() { return std::string("\n Derived1 here with count = ") + instanceCount(); } }; class Derived2 : public Base { public: virtual std::string say() { return std::string("\n Derived2 here with count = ") + instanceCount(); } }; void main() { std::cout << "\n MT2Q3 - Factory for Singleton"; std::cout << "\n ===============================\n"; try { factory f1; // should get the same static Base::count of 1 Base* pB1 = f1.Create(); std::cout << pB1->say(); Base* pB2 = f1.Create(); std::cout << pB2->say(); if(pB1 != pB2) throw std::exception("Not a singleton!"); std::cout << std::endl; // should get the same static Base::count of 2 factory f2; Base* pB3 = f2.Create(); std::cout << pB3->say(); Base* pB4 = f2.Create(); std::cout << pB4->say(); if(pB3 != pB4) throw std::exception("Not a singleton!"); if(pB1 == pB3) throw std::exception("new derived class should get new singleton"); std::cout << std::endl; factory f3; Base* pB5 = f3.Create(); std::cout << pB5->say() << "\n\n"; } catch(std::exception& ex) { std::cout << "\n\n " << ex.what() << "\n\n"; } }