Poco::DynamicFactory Demo 【转】
原文:http://blog.csdn.net/huang_xw/article/details/8174586
DynamicFactory.cc
#include <iostream> #include <cstdlib> #include <assert.h> #include <Poco/DynamicFactory.h> namespace DF { class Base { public: Base() { } virtual ~Base() { } }; class A: public Base { public: void print(){std::cout << "My name is A Class!" << std::endl;} }; class B: public Base { }; } void test_DynamicFactory() { // 创建一个工厂实例. Poco::DynamicFactory<DF::Base> dynFactory; // 类A注册到工厂, 注册名为A, 当然也可以为其他的名字. dynFactory.registerClass<DF::A>("A"); dynFactory.registerClass<DF::B>("B"); assert (dynFactory.isClass("A")); assert (dynFactory.isClass("B")); // 通过工厂, 创建类A的对象. DF::A* a = dynamic_cast<DF::A*>(dynFactory.createInstance("A")); std::auto_ptr<DF::A> ap(dynamic_cast<DF::A*>(dynFactory.createInstance("A"))); a->print(); ap->print(); try { // 已经注册过了, 将抛出异常. dynFactory.registerClass<DF::A>("A"); } catch (...) { std::cout << "exception" << std::endl; } try { // 反注册类B的 dynFactory.unregisterClass("B"); // 未注册的类, 注册时将抛出异常. std::auto_ptr<DF::B> b(dynamic_cast<DF::B*>(dynFactory.createInstance("B"))); } catch (Poco::NotFoundException&) { std::cout << "exception" << std::endl; } } int main ( int argc, char *argv[] ) { test_DynamicFactory(); return EXIT_SUCCESS; } /* ---------- end of function main ---------- */
结果:
[root@slayer ptn]# g++ DynamicFactory.cc -lPocoFoundation -o df [root@slayer ptn]# ./df My name is A Class! My name is A Class! exception exception