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
FileWriter
with existing formatters:
JsonFormatter jf; FileWriter fw("test.txt", jf);
- Initialize
FileWriter
with r-values:
FileFormatter fw("test.txt", CsvFormatter());
- There should be a hierarchy of
Formatter
classes (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); }
Formatter
may 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:
FileFormatter
should store a pointer toIFormatter
(base class) because it'll be abstract class- Having a pointer to
IFormatter
will require passing pointers inFileWriter
constructor, 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.