vendredi 26 octobre 2018

How to maintain consistency of data between classes while maximizing encapsulation?

I am relatively new to c++ and am interested in the best way to maintain consistency of a data structure that is being modified/read by classes that do not know of each other. I have class A (app), class B (builder), class C (calculator) and struct D (data). A contains instances of B, C and D. C performs calculations on D, oftentimes replacing D entirely with a new object of type D. B is only reading from D and never changing it. Classes C and B do not know about each other and I would prefer it that way. How do I ensure that B has consistent knowledge of D even as it is modified by C.

My current solution to this is to pass a pointer of D into C to be modified as needed. A const reference of D is passed into B since it does not need to modify data. Pseudo-code below:

struct D{
  int _i;
  int _j;
  D(int i, int j) : _i(i), _j(j){}
}

class A{
public:
  A() : _myDataPtr(new D(x, y)), _myBuilder(*_myDataPtr),  
        _myCalculator(_myDataPtr){

    _myCalculator.manipulateData();
    _myBuilder.showData();

  }

private:
  D* _myDataPtr;
  B _myBuilder;
  C _myCalculator;
}

class B{
public:
  B(const D& data) : _data(data){}

  void showData(){
    cout << _data._i << _data._j;
  }
private:
  const D& _data;
}

class C{
public:
  C(D* data) : _data(data){}

  void manipulateData(){
    if (sometimes){
      _data = new D(u,v);
    }else{
      _data->_i = u;
      _data->_j = v;
    }
private:
  D* _data;
}

int main(){
  A a();
}

I know there are many different ways to pass D around between the other classes. Is it better to instantiate B with a copy of C and have the data D entirely contained in C? would that not ben an innapropriate solution if encapsulation was high priority?

I have read that use of dynamically allocated memory using new should be minimized, so is there a way of doing that here that would be more appropriate? Is this current incarnation going to be prone to memory leaks because of the use of new here?

Is the use of shared_ptr or unique_ptr warranted here? Any tips or suggestions would be very welcome.

Aucun commentaire:

Enregistrer un commentaire