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

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

提前致谢...

我在下面添加了类定义的简化版本。我知道此处SalesTeam类未与SalesPerson分离。

// 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();
};

最佳答案

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

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();
};

10-08 13:33