Y
Y
yarushin_a2020-04-09 21:07:01
C++ / C#
yarushin_a, 2020-04-09 21:07:01

How to implement the communication of objects with data of a previously unknown type through an interface?

There are 2 objects - A and B, inherited from the same interface. Object A stores some data that B requests. What we managed to achieve is that B requests data and receives them, but as you can see from the code, this is an exchange of strings, it is necessary that the data type be unknown in advance. I understand that for this the GetMessage and SendMessage interface methods must be templated, but they cannot be both templated and virtual at the same time.

#include <iostream>
#include <vector>

using namespace std;


class BaseClass;

//=========================================

class Mediator{

public:
    void addObj(BaseClass *obj){
        this->objList.push_back(obj);
    }

    BaseClass* getObj(int index){
        return objList[index];
    }

    template<typename T>
    void Redirect(T message, BaseClass *sender){
        sender->GetMessage(message);
    }

private:
     vector<BaseClass*> objList;
};


//=========================================

class BaseClass {
public:
    Mediator *mediator;
    virtual void SendMessage(string action) = 0;
    virtual void GetMessage(string action) = 0;
};


//=========================================

class B : public BaseClass{
public:
    B(Mediator *mediator){

        this->mediator = mediator;
        this->mediator->addObj(this);
    }

    void SendMessage(string action) override{
        this->mediator->Redirect(action,this->mediator->getObj(0));
    }
    void GetMessage(string action) override{
        cout << "I'm B - " << action << endl;
    }
};

//=========================================

class A : public BaseClass{
public:
    string getX(){return this->x;}
    A(){

       this->mediator = new Mediator();
        this->mediator->addObj(this);

    }

    void SendMessage(string action) override{
        this->mediator->Redirect(action,this->mediator->getObj(1));
    }

    void GetMessage(string action) override{
        if(action == "getX"){
            this->SendMessage(getX());
        }
    }
private:
    string x = "5";
};



int main()
{

    A *a = new A();
    B *b = new B(a->mediator);
    b->SendMessage("getX");
    return 0;
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question