design patterns - Initialization class for other classes - C++ -


i initialize 2 classes(say class aregister, class bregister) registers values(a,b). want initialize these 2 classes super(?) class( class registerall).

ex: registerall class initialize aregister , bregister. using module need not create objects of aregister , bregister individually, instead can create object of registerall.

i these registrations in constructor. needs done create objects of registerall class , registrations happens automatically.

we not use exceptions in our project. if there error in registration not possible know.

should have separate member function registration or let constructor registration.

i newbie oo design. feel wrong design, helpful if can point right approach.

the best way using crtp (curiously recurring template pattern), derived classes aregister , bregister pass template arguments base class registerall. this:

class registerall { public:     template<class derivedtype>     derivedtype *createtype()     {         registerall *r = (*(m_creators[derivedtype::id]))();         return dynamic_cast<derivedtype *>(r); //static_cast work if didn't make mistake     } protected:     static std::map<int,registerall *(*)()> m_creators; };  std::map<int,registerall *(*)()> registerall::m_creators = std::map<int,registerall *(*)()>();  template<class derived> class crtpregisterall : public registerall { public:     static bool register()      {         registerall::m_creators.push_back(std::make_pair(derived::id,derived::create);         return true;     }  private:     static bool m_temp; };  template<class derived> bool crtpregisterall<derived>::m_temp = crtpregisterall<derived>::register();  class registera : public crtpregisterall<registera> { private:     static registera *create()      {         //do initialization stuff here         return new registera;     }  public:     static const int id = 0; }; 

now initialization of static variable m_temp in crtpregisterall pushes creator function each derived type onto registerall's list. not design have registerall know derived classes (it isn't extensible). way actual creation method can implemented in each derived class , creator function automatically registered in registerall. 1 of main advantages of crtp derived classes don't need know how register base class' list, done them. error handling can implemented in each derived class' creator functions. there better ways handle id issue don't want here. if want simpler method suggest reading factory design pattern.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -