What is a good design pattern for creating files?

In one application, I have the task of creating files that will be used by a third party. There are actually three different types of content in files:

  • A list of employee cards for sending data to a third-party application;
  • List of employee cards for collecting biometrics;
  • Interval of numbers.

At the moment, I have only one class called FileGenerator (a common, bad name that I think), which receives data and creates a file with some name conventions (clock code, file type, date and hour).

Is there a good design template to ensure that the naming convention remains and separate the generation of files in specific classes for each file type?

Is there a good way to reuse the code that the file generates (not to be repeated in specific classes)?

This is part of an existing class:

 class FileGenerator { private List<String> contentOfFile; private String fileName; //I - include employees //C - change employees //R - remove employees //B - collect biometry //N - interval of numbers private String option; private void getFileName(){ ... } //this assure the file name convention public void generate(){ ... } //this generate the file with content } 

What I think so far:

  • Create an abstract class to preserve the naming convention. And write the contents to a file.
  • Create a factory class that will know all file types (factory is a good template to use here?).
  • Inject specific classes into file types to determine what content will be recorded.
+4
source share
1 answer

More or less what you said:

1 - template template template for recording a file. I think something like this:

 public abstract class EmployeeCardFileGenerator { /** * @return the generated file name */ public abstract String getFileName(/*any params you need to get the file name*/); /** * @return the line corresponding to the given data record */ public abstract String getLine(EmployeeCardData data); /** * @return the header to be appended at the beginning of the file */ public abstract String getHeader(/*any header params*/); /** * @return the footer to be appended at the end of the file */ public abstract String getFooter(/*any footer params*/); public void generateFile(/*any params*/) { List<EmployeeCardData> data = queryData(); File f = createFile(); PrintWriter pw = getWriter(f); pw.println(getHeader()); for(EmployeeCardData ec : data) { pw.println(getLine(ec)); } pw.println(getFooter()); cleanup(); } } 

2. You would have different implementations of them issued by the factory.

0
source

Source: https://habr.com/ru/post/1395247/


All Articles