This question was a precursor to the current one. Need to come up with better OOP design.
Problem desription: there is a class called FileWriter which uses object of class Formatter to write a dictionary of key-values (std::map<std::string, double>) into a file.
Requirements:
- Initialize
FileWriterwith existing formatters:
JsonFormatter jf;
FileWriter fw("test.txt", jf);
- Initialize
FileWriterwith r-values:
FileFormatter fw("test.txt", CsvFormatter());
- There should be a hierarchy of
Formatterclasses (derived from interfaceIFormatter) to allow the following:
{
CsvFormatter cf(2, "\t"); // 2 digits precision, tab-separated
FileWriter fwCsv("test.txt", csv);
}
{
JsonFormatter jf(2, true); // 2 digits precision, compact JSON formatting
FileWriter fwJson("test.txt", jf);
}
Formattermay store additional parameters such as precision, separator symbol (for CSV) or compact formatting flag (for JSON).
What would be the proper design pattern and correct implementation for such problem? My main concerns are:
FileFormattershould store a pointer toIFormatter(base class) because it'll be abstract class- Having a pointer to
IFormatterwill require passing pointers inFileWriterconstructor, which will impose additional implementation complexity in order to meet requirement 1
How it's done currently in C++? Does this case fall under source/sink idiom? Any links for existing solutions are welcome as well.
Aucun commentaire:
Enregistrer un commentaire