[英]What is a good design pattern for file creation?
In one app, I have a task to create files that will be used by a third party. 在一个应用程序中,我有一个任务是创建将由第三方使用的文件。 Actually there are three distinct types of content in the files:
实际上文件中有三种不同类型的内容:
For now I have just one class called FileGenerator
(generic, bad name I think) that receives the data and creates a file with some name convention (code of clock, type of file, date and hour). 现在我只有一个名为
FileGenerator
类(我认为通用的,坏名称)接收数据并创建一个具有一些名称约定的文件(时钟代码,文件类型,日期和小时)。
There's a good design pattern to ensure that the file name convention will remains and to split the generation of files in specific classes for each type of file? 有一个很好的设计模式,以确保文件名约定将保留,并为每种类型的文件分割特定类中的文件生成?
There's a good way to reuse the code that generates the file (don't repeating myself in the specific classes)? 有一种很好的方法可以重用生成文件的代码(不要在特定的类中重复自己)?
This is part of the 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: 到目前为止我的想法:
abstract class
to hold the name convention. abstract class
来保存名称约定。 And to write the content to a file. factory class
that will know all the types of files (factory is a good pattern to use here?). factory class
,知道所有类型的文件(工厂是一个很好的模式在这里使用?)。 More or less what you said: 或多或少你说的话:
1-The template method pattern for writing the file. 1 - 用于写入文件的模板方法模式。 I am thinking 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 these, dispensed by a factory. 2-您将拥有不同的实施方案,由工厂分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.