I am coding a directory parser utility, which scans different directories for different type of files.
Now a straightforward implementation urges me to do the following.
Have a list of directories to parse, loop over them and pass it to a method that actually does the file I/O and other logic and returns the result.
List<Dir> dirList;
//loop over the list and call parseDirecotry()
parseDirectory(Dir dirToParse){
//do file io
if (filename.matches("pattern"){
//proceed)
}
}
Each directory that’s scanned requires me to filter out certain files. So now
for certails dir the match pattern will vary, now either I could keep adding the match pattern based on the type of directory in if else logic.
Or
I could take the pattern out make of it a part of the Dir object, make it abstract, have specific directory implementations hold the specific match pattern.
This way I don’t have to touch the parseDirectory method every time I have a new directory to scan.
Question is: is there some design pattern that I could possible leverage here? What are you views about the above program to interface way and do you think if it would make sense to move the parseDirectory() method up to the abstract directory class as well?
OK I will propose my solution
1) Create an interface called IFileProcessor having method processFile
2) Create singleton classes specific to document types implementing IFileProcessor. So the classes will be DocFileProcessor, XLSFileProcessor etc and each class will have its own specific implementation of processFile API.
3)Create a factory class say FileProcessorFactory. It should have an API called
IFileProcessor getFileProcessor(String fileTypeExtension). This API will take file extension as input and return the DocFileProcessor, XLSFileProcessor etc for input doc, xls etc.4) In your loop call getFileProcessor of FileProcessorFactory giving it input. Now call processFile on returned instance.
Having this design decouples the logic of if-else to Factor allowing you logic to remain independent of the file types.