interface - C++ multiple data sources within class -
i wonder how 1 go adding different data sources existing code. example, let's have piece of code:
//datafromfile.cpp #include "data.h" class datafromfile { public: datafromfile() { filename = ""; } ~datafromfile() { delete data; } void loadvalue(const char *filename) { //getting data file } void printdata() { data->printdata(); } private: string filename; data *data; }; //source.cpp #include <iostream> #include "datafromparameter.h" int main(int argc, char **argv) { datafromfile olddata; olddata.loadvalue("example.txt"); olddata.printdata(); return 0; }
and need create class datafromdatabase or datafromparameter without changing way datafromfile works (this code used throughout various programs , going through code out of question). creating interface seemed way go, came solution:
//idata.h #include "data.h" class idata { public: idata() { data = null; } virtual ~idata() = 0 { delete data; } void printdata() { if (data != null) data->printdata(); } protected: data *data; } //datafromparameter.h #include "idata.h" class datafromparameter : public idata { public: datafromparameter(const int value) { this->data = new data(value); } ~datafromparameter() {} }; //datafromfile.h #include "idata.h" class datafromfile : public idata { public: datafromfile() { filename = ""; } datafromfile(const char *filename) { loadvalue(filename); } ~datafromfile() {} void loadvalue(const char *filename) { //getting data file } private: string filename; }
as can see idata , datafromparameter new classes , added methods datafromfile. creating new objects , calling methods:
//source.cpp #include <iostream> #include "datafromparameter.h" int main(int argc, char **argv) { //source: file (the old way) datafromfile olddata; olddata.loadvalue("example.txt"); olddata.printdata(); //source: file (the new way) idata *newdata1 = new datafromfile("example.txt"); newdata1->printdata(); delete newdata1; //source: parameter idata *newdata2 = new datafromparameter(atoi(argv[1])); newdata2->printdata(); delete newdata2; return 0; }
it works, nevertheless i'm not happy it; datafromfile class code looks messy - know why looks way sure else pretty confused going on in there.
my question is: there better way go here? sloppiness necessary (given circumstances) or missing obvious solution problem?
Comments
Post a Comment