jeudi 14 mars 2019

In c++, How can I share data between two classes efficiently?

include "dataConsumer.h"

#include 
#include 

DataConsumer::DataConsumer(){}
DataConsumer::~DataConsumer(){}

void DataConsumer::Body()
{
    std::cout << "DataConsumer Start" << std::endl;

    while (1)
    {
        //I want to get providerData_ of DataProvide class in here

        Sleep(1000);
    }
}


#include "dataProvider.h"

#include 
#include 

DataProvider::DataProvider(){}
DataProvider::~DataProvider(){}

void DataProvider::Body()
{
    std::cout << "DataProvider Start" << std::endl;

    while (1)
    {
        //Update data in here
        providerData_++;

        Sleep(1000);
    }
}

There are two classes. And I want to get providerData_ of dataProvider class in dataConsumer class.

To resolve this situation, I thought the following is one solution. I made singleton dataTransfer class like below. But I am not sure whether this is a general solution in c++. If you know a good solution(or design pattern) to resolve my situation, please advise to me.

#ifndef DATATRANSFER_H
#define DATATRANSFER_H

class DataTransfer
{
public:
    static DataTransfer* getInstance()
    {
        static DataTransfer instance;
        return &instance;
    }
    void GetData(unsigned int *data)
    { 
        if(data)
            *data = data_;
    }
    void SetData(unsigned int *data)
    { 
        if(data)
            data_ = *data;
    }

private:
    DataTransfer(){}
    ~DataTransfer(){}

    unsigned int data_;
};

#endif


#include "dataConsumer.h"
#include "dataTransfer.h"

#include 
#include 

DataConsumer::DataConsumer(){}
DataConsumer::~DataConsumer(){}

void DataConsumer::Body()
{
    unsigned int data = 0;
    std::cout << "DataConsumer Start" << std::endl;

    while (1)
    {
        //I want to get providerData_ of DataProvide class in here
        DataTransfer::getInstance()->GetData(&data);

        std::cout << "DataConsumer data:" << data << std::endl;

        Sleep(1000);
    }
}

#include "dataProvider.h"
#include "dataTransfer.h"

#include 
#include 

DataProvider::DataProvider() : providerData_(0)
{
}

DataProvider::~DataProvider(){}

void DataProvider::Body()
{
    std::cout << "DataProvider Start" << std::endl;

    while (1)
    {
        //Update data in here
        providerData_++;

        DataTransfer::getInstance()->SetData(&providerData_);

        Sleep(1000);
    }
}

Aucun commentaire:

Enregistrer un commentaire