“继承”另一个(1:N)关系的关系

时间:2018-07-03 07:41:36

标签: c++ design-patterns data-structures game-engine one-to-many

我想要一个支持这些特定的1:N关系的数据结构:-
1#。 Human 加薪 0-N Human
2#。 Human 0-N Dog
3#。 Human 耕种 0-N Tree
4#。 Dog 是0-N Parasites的房屋。

enter image description here

注意:
-这些关系中的国家都是暂时的,例如Human1可能加薪 Human2,但是一年之后,Human1可能会放弃Human2
-所有对象均继承自BaseObject,并具有唯一的int ID。

在以上所有关系中,我希望能够支持以下功能:-
F1。添加关系例如human_dog->addRelation(Human* a,Dog* b)
F2。删除关系human_dog->removeRelation(Human* a,Dog* b)
F3。查询所有孩子human_dog->getAllChildren(Human*)
F4。查询所有父项human_dog->getAllParents(Dog*)
F5。检查父母是否有> = 1个孩子
F6。检查孩子是否有> = 1个父母
F7。删除所有父母的孩子
F8。删除一个孩子的所有父母

这可以通过std::unordered_map或更容易定制的东西来实现。

这是困难的部分

我想将关系1#,2#,3#(即所有实线)标记为 Feed
它必须以 聚集 样式支持功能F3-F8。

例如:-

  • feed->getAllChildren(BaseObject* b)
    如果b是人类,则必须返回b的所有抚养耕种的孩子。
  • feed->removeAllParent(BaseObject* b)
    如果b是狗,它将像cultivate->removeAllParent(b)一样起作用。

总而言之,我希望能够轻松注入这样的 聚合
例如调用:-

void BaseObject::declareForFreedom(){
    feed->removeAllParent(this);
}

上面的示例仅显示4个关系和1个间接级别。
在我的真实情况下,这种继承/间接关系有8-10个关系和3-4个级别。

问题

什么是适合这种情况的数据结构/设计模式?

我目前为1#-4#创建一个自定义的1:N关系,并对每个 feed 函数进行硬编码。这很乏味。
我已经猛烈抨击了几个月,但没有发现任何看起来优雅的实现。

演示

http://coliru.stacked-crooked.com/a/1f2decd7a8d96e3c

基本类型:-

#include <iostream>
#include <map>
#include <vector>
enum class Type{
    HUMAN,DOG,TREE,PARASITE,ERROR
}; //for simplicity
class BaseObject{public: Type type=Type::ERROR; };
class Human : public BaseObject{
    public: Human(){ type=Type::HUMAN; }    
};
class Dog : public BaseObject{
    public: Dog(){ type=Type::DOG; }    
};
class Tree : public BaseObject{
    public: Tree(){ type=Type::TREE; }    
};
class Parasite : public BaseObject{
    public: Parasite(){ type=Type::PARASITE; }    
};

基本的1:N地图

template<class A,class B> class MapSimple{
    std::multimap<A*, B*> aToB;
    std::multimap<B*, A*> bToA;
    public: void addRelation(A* b1,B* b2){
        aToB.insert ( std::pair<A*,B*>(b1,b2) );   
        bToA.insert ( std::pair<B*,A*>(b2,b1) );   
    }
    public: std::vector<B*> queryAllChildren(A* b1){
        auto ret = aToB.equal_range(b1);
        auto result=std::vector<B*>();
        for (auto it=ret.first; it!=ret.second; ++it){
            result.push_back(it->second);
        }
        return result;
    }
    public: void removeAllParent(B* b){
        if(bToA.count(b)==0)return;
        A* a=bToA.find(b)->second;
        bToA.erase(b);
        auto iterpair = aToB.equal_range(a);
        auto it = iterpair.first;
        for (; it != iterpair.second; ++it) {
            if (it->second == b) { 
                aToB.erase(it);
                break;
            }
        }
    }
    //.. other functions 
};

这是数据库实例和聚合:-

MapSimple<Human,Human> raise;
MapSimple<Human,Dog> has;
MapSimple<Human,Tree> cultivate;
MapSimple<Dog,Parasite> isHouseOf;
class Feed{
    public: void removeAllParent(BaseObject* b1){
        if(b1->type==Type::HUMAN){
            raise.removeAllParent(static_cast<Human*>(b1));
        } 
        if(b1->type==Type::DOG){
            has.removeAllParent(static_cast<Dog*>(b1));
        }
        //.... some other condition (I have to hard code them - tedious) ...
    }
    //other function 
};
Feed feed;

用法

int main(){
    Human h1;
    Dog d1,d2;

    has.addRelation(&h1,&d1);
    has.addRelation(&h1,&d2);
    auto result=has.queryAllChildren(&h1);
    std::cout<<result.size(); //print 2
    feed.removeAllParent(&d1);
    result=has.queryAllChildren(&h1);
    std::cout<<result.size(); //print 1
}

2 个答案:

答案 0 :(得分:1)

直接实现有什么问题?

例如: BaseObject.hpp

#include <vector>

template<class T>
using prtVector = std::vector<T*>;

class BaseObject {
public:
    virtual prtVector<BaseObject> getAllParents() const = 0;
    virtual prtVector<BaseObject> getAllChilderen() const = 0;
    virtual void removeAllParents() = 0;
    virtual void removeAllChildren() = 0;
};

Human.hpp

#include "BaseObject.hpp"
#include "Tree.hpp"
#include "Dog.hpp"
class Tree;
class Dog;

class Human : public BaseObject {
public:
    prtVector<BaseObject> getAllParents() const override;
    prtVector<BaseObject> getAllChildren() const override;

    void removeAllParents() override;
    void removeAllChildren() override ;

    friend class Dog;
    friend class Tree;
    template<class A, class B>
    friend void addRelation(A* a, B* b);
private:
    void addParent(Human* const);
    void removeParent(Human const* const);
    void addChild(Human* const);
    void removeChild(Human const* const);
    void addChild(Tree* const);
    void removeChild(Tree const* const);
    void addChild(Dog* const);
    void removeChild(Dog const* const);
private:
    prtVector<Human> parents;
    prtVector<Human> children;
    prtVector<Tree> plants;
    prtVector<Dog> pets;
};

Human.cpp

#include "Human.hpp"

prtVector<BaseObject> Human::getAllParents() const {
    prtVector<BaseObject> result(std::cbegin(parents), std::cend(parents));
    return result;
}

prtVector<BaseObject> Human::getAllChildren() const {
    prtVector<BaseObject> result(std::cbegin(children), std::cend(children));
    result.insert(std::end(result), std::cbegin(pets), std::cend(pets));
    result.insert(std::end(result), std::cbegin(plants), std::cend(plants));
    return result;
}

void Human::removeAllParents() {
    for (auto parent : parents) { parent->removeChild(this); }
    parents.clear();
}

void Human::removeAllChildren() {
    for (auto child : children) { child->removeParent(this); } children.clear();
    for (auto pet : pets) { pet->removeParent(this); } pets.clear();
    for (auto plant : plants) { plant->removeParent(this); } plants.clear();
}

void Human::addParent(Human* const parent) { parents.push_back(parent); }

#include <algorithm>
void Human::removeParent(Human const* const parent) {
    auto it = std::find(std::cbegin(parents), std::cend(parents), parent);
    if (it != std::cend(parents)) parents.erase(it);
}
void Human::addChild(Human* const child) { children.push_back(child); }

等,等等...

与其他类型相同。...

main.cpp

#include "Human.hpp"
#include "Dog.hpp"

template<class A, class B>
void addRelation(A* a, B* b)
{
    a->addChild(b);
    b->addParent(a);
}

template<class A>
prtVector<BaseObject> queryAllChildren(A* obj)
{
    return obj->getAllChilderen();
}

template<class A>
void removeAllParents(A* obj)
{
    obj->removeAllParents();
}

#include <iostream>
int main() {
    Human h1;
    Dog d1, d2;

    addRelation(&h1, &d1);
    addRelation(&h1, &d2);
    auto result = queryAllChildren(&h1);
    std::cout << result.size() << "\n"; //print 2
    removeAllParents(&d1);
    result = queryAllChildren(&h1);
    std::cout << result.size() << "\n"; //print 1

    std::cin.ignore();
}

恕我直言,这给出了可读且可维护的代码。可能可以有所优化。但是至少从代码中关系很清楚。

答案 1 :(得分:1)

编辑

Jarod42 in this topic建议使用更好的代码。 C ++ 17风格:

break

旧代码:(我的尝试)

好的,因为您不想重复的代码,所以我一直将此项目作为元编程/可变模板的初次经验。这就是我得到的:

#include <algorithm>
#include <tuple>
#include <vector>

class BaseObject {
public:
    virtual ~BaseObject() = default;
    virtual std::vector<BaseObject*> getAllParents() const = 0;
    virtual std::vector<BaseObject*> getAllChildren() const = 0;
    virtual void removeAllParents() = 0;
    virtual void removeAllChildren() = 0;
};

template<typename TParentTuple, typename TChilderenTuple>
class Obj;

template<typename... ParentTags,
         typename... ChildTags>
class Obj<std::tuple<ParentTags...>, std::tuple<ChildTags...>> : public BaseObject
{
    std::tuple<std::vector<typename ParentTags::obj_type*>...> parents;
    std::tuple<std::vector<typename ChildTags::obj_type*>...> children;

public:

    template <typename T>
    void addParent(T* parent) { std::get<std::vector<T*>>(parents).push_back(parent); }

    template <typename T>
    void removeParent(const T* parent) {
        auto& v = std::get<std::vector<T*>>(parents);
        auto it = std::find(std::cbegin(v), std::cend(v), parent);
        if (it != std::cend(v)) { v.erase(it); }
    }

    template <typename T>
    void addChild(T* child) { std::get<std::vector<T*>>(children).push_back(child); }

    template <typename T>
    void removeChild(const T* child) {
        auto& v = std::get<std::vector<T*>>(children);
        auto it = std::find(std::cbegin(v), std::cend(v), child);
        if (it != std::cend(v)) { v.erase(it); }
    }

    std::vector<BaseObject*> getAllParents() const override {
        std::vector<BaseObject*> res;

        std::apply([&](auto&... v){ (res.insert(res.end(), v.begin(), v.end()), ...); },
                   parents);
        return res;
    }
    std::vector<BaseObject*> getAllChildren() const override {
        std::vector<BaseObject*> res;

        std::apply([&](auto&... v){ (res.insert(res.end(), v.begin(), v.end()), ...); },
                   children);
        return res;
    }

    void removeAllParents() override {
        std::apply(
            [this](auto&... v)
            {
                [[maybe_unused]] auto clean = [this](auto& v) {
                    for (auto* parent : v) {
                        parent->removeChild(this);
                    }
                    v.clear();
                };
                (clean(v), ...);
            },
            parents);
    }

    void removeAllChildren() override {
        std::apply(
            [this](auto&... v)
            {
                [[maybe_unused]] auto clean = [this](auto& v) {
                    for (auto* child : v) {
                        child->removeParent(this);
                    }
                    v.clear();
                };
                ( clean(v), ...);
            },
            children);
    }
};

struct Human_tag;
struct Tree_tag;
struct Dog_tag;
struct Parasite_tag;

using Human = Obj<std::tuple<>, std::tuple<Tree_tag, Dog_tag>>;
using Tree = Obj<std::tuple<Human_tag>, std::tuple<>>;
using Dog = Obj<std::tuple<Human_tag>, std::tuple<Parasite_tag>>;
using Parasite = Obj<std::tuple<Dog_tag>, std::tuple<>>;

struct Human_tag { using obj_type = Human; };
struct Tree_tag { using obj_type = Tree; };
struct Dog_tag { using obj_type = Dog; };
struct Parasite_tag { using obj_type = Parasite; };

template<class A, class B>
void addRelation(A* a, B* b)
{
    a->addChild(b);
    b->addParent(a);
}

#include <iostream>
int main() {
    Human h1;
    Dog d1, d2;

    addRelation(&h1, &d1);
    addRelation(&h1, &d2);
    auto result = h1.getAllChildren();
    std::cout << result.size() << "\n"; //print 2
    d1.removeAllParents();
    result = h1.getAllChildren();
    std::cout << result.size() << "\n"; //print 1
}

请询问任何不清楚的问题,因为在过去的24小时里我一直在学习很多新东西,所以我不知道从哪里开始解释。