Main Page   Class Hierarchy   Compound List   File List   Compound Members  

Factory.h

00001 #ifndef Factory_H
00002 #define Factory_H
00003 
00004 #include <map>
00005 #include <string>
00006 
00007 using namespace std;
00008 
00010 /*
00011   The "factory" pattern is a technique for creating new
00012   instances of objects which defines an abstract interface,
00013   (represented by the "Make" module). The subclasses of
00014   factory decide which class to instantiate.
00015   
00016 
00017   Each subclass of factory "registers" itself at compile time;
00018   therefore, the addition of a new factory requires no change
00019   the parent class. 
00020 
00021   \author Gilberto Camara
00022 */
00023 template <class T, class Arg>
00024 class Factory
00025 {
00026 public:
00027 
00029         typedef map<string, Factory<T,Arg>* > FactoryMap; 
00030 
00032         static FactoryMap& instance ()
00033         { 
00034                 static FactoryMap Fmap_;
00035                 return Fmap_;
00036                 
00037         }
00038         
00040         Factory (const string& name):Fname_(name)
00041         {
00042                 Factory<T,Arg>::instance()[name] = this;
00043         };
00044 
00045 
00046         virtual ~Factory() 
00047         {
00048                 // Remove the object from the factory dictionary
00049                 // Fmap_.erase ( Fname_ );
00050         };
00051 
00052 
00054         static T* make  ( string name, const Arg& arg ) 
00055         {
00056                 // try to find the name on the factory dictionary
00057                 typename FactoryMap::iterator i = Factory<T,Arg>::instance().find ( name );
00058 
00059                 // Not found ?  return the Default Object   
00060                 //if ( i == Factory<T,Arg>::instance().end() )
00061                 //      return T::DefaultObject( arg );
00062 
00063                 // Create an object, based on the input parameters
00064                 return (*i).second->build ( arg );
00065                 return 0;
00066         };
00067 
00069         static T* make  ( Arg arg ) 
00070         {
00071                 string name = arg.decName();
00072 
00073                 // try to find the name on the factory dictionary
00074                 typename FactoryMap::iterator i = Factory<T,Arg>::instance().find ( name );
00075 
00076                 // Not found ?  return the Default Object   
00077                 if ( i == Factory<T,Arg>::instance().end() )
00078                         return T::DefaultObject( arg );
00079 
00080                 // Create an object, based on the input parameters
00081                 return (*i).second->build ( arg );
00082                 return 0;
00083         };
00084 
00085 
00086 protected:
00087 
00089     virtual T* build ( const Arg& arg ) = 0;
00090 
00091 private:
00092         string  Fname_;
00093 };
00094 
00095 
00096 #endif

Generated on Thu Apr 8 15:04:10 2004 for SOMCode by doxygen1.2.18