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

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

问题描述

我正在寻找有关解耦两个 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天全站免登陆