1

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:

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

Community
  • 1
  • 1
peetonn
  • 2,942
  • 4
  • 32
  • 49

0 Answers0