store many of relation 1:1 between various type of objects : decoupling & high performance

前端 未结 6 1251
夕颜
夕颜 2021-02-01 08:26

I have 300+ classes. They are related in some ways.

For simplicity, all relation are 1:1.
Here is a sample diagram.

(In real case, there are aroun

6条回答
  •  悲哀的现实
    2021-02-01 09:04

    My suggestion:

    1. Add a common base class.
    2. Add a list of parents and children to the base class.
    3. Add functions to add, remove, insert, query parents and children to the base class.
    4. Add higher level non-member functions as needed.

    class Base
    {
       public:
          virtual ~Base();
    
          // Add "child" to the list of children of "this"
          // Add "this" to the list of parents of "child"
          void addChild(Base* child);
    
          // Remove "child" from the list of children of "this"
          // Remove "this" from the list of parents of "child"
          void removeChild(Base* child);                                 
    
          std::vector& getParents();
          std::vector const& getParents() const;
    
          std::vector& getChildren();
          std::vector const& getChildren() const;
    
       private:
        std::vector parents_;
        std::vector chilren_;    
    };
    

    Now you can implement higher level functions. E.g.

    // Call function fun() for each child of type T of object b.
    template 
    void forEachChild(Base& b, void (*fun)(T&))
    {
       for ( auto child, b.getChildren() )
       {
          T* ptr = dynamic_cast(child);
          if ( ptr )
          {
             fun(*ptr);
          }
       }
    }
    

    To query the unique egg from a hen, you could use a generic function template.

    template 
    T* getUniqueChild(Base& b)
    {
       T* child = nullptr;
       for ( auto child, b.getChildren() )
       {
          T* ptr = dynamic_cast(child);
          if ( ptr )
          {
             if ( child )
             {
                // Found at least two.
                // Print a message, if necessary.
                return NULL;
             }
    
             child = ptr;
          }
       }
    
       return child;
    }
    

    and then use it as:

    hen* henptr = ;
    egg* eggptr = getUniqueChild(*henptr);
    

提交回复
热议问题