在C ++中如何最好地解耦必须相互维护引用集合的2个类 [英] In C++ how to best decouple 2 classes that must maintain collections of references to each other

查看:287
本文介绍了在C ++中如何最好地解耦必须相互维护引用集合的2个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关解耦两个C ++类的最优雅,最安全的方法的建议,这两个C ++类维护着指向彼此类型的指针的集合.

I am looking for advice on the most elegant and secure way to decouple two C++ classes that maintain collections of pointers to each other's types.

我最近使用一个通用的多态基类来实现它,并被告知这不是一个令人满意的解决方案.我渴望学习实现这一目标的其他方法.

I implemented it recently using a common base class for polymorphism and was told that it was an unsatisfactory solution. I am eager to learn other ways this can be achieved.

预先感谢...

我在下面添加了类定义的简化版本.我知道SalesTeam类在这里没有与SalesPerson解耦.

I have added a simplified version of the class definitions below. I am aware that the SalesTeam class is not decoupled from SalesPerson here.

// Global Vectors
vector<Customer *> v_Customer;          
vector<SalesPerson *> v_SalesPerson;  
vector<SalesTeam *> v_SalesTeam;


class Person {    // Base Class
};

class Customer: public Person {
private:
    const Person *contact;         // This is the SalesPerson that serves the Customer
public:
    Customer(const int aBirthYear);
    virtual ~Customer() {}
};

class SalesPerson: public Person {
private:
    vector<Person *> v_Client;  // These are the customers that the SalesPerson serves
public:
    SalesPerson();
    virtual ~SalesPerson(){};
};

class SalesTeam {
private:
    vector<SalesPerson *> v_TeamMember;  // These are the sales people in the SalesTeam
public:
    SalesTeam();
};

推荐答案

可以使用调解器模式来解决此分离问题吗?代码示例:

can you use mediator pattern to handle this decouple issue? code example:

class Mediator
{
    private:
        //store your relationship in this class
}

class SalesPerson: public Person {
private:
    Mediator mediator;
public:
    SalesPerson();
    virtual ~SalesPerson(){};
};

class SalesTeam {
private:
    Mediator mediator;
public:
    SalesTeam();
};

这篇关于在C ++中如何最好地解耦必须相互维护引用集合的2个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆