Re: design pattern for a file converter...
On 12/9/2010 12:08 PM, Tom Whittaker wrote:
I am creating an application that will allow the user to specify
different types of input files, and then my application reads in the
file, parses it,
First, I think design patterns are somewhat low level implementations
that depend a lot on how the design is structured and what sorts of
requirements you have over all. Just "read a file" doesn't really imply
Strategy Pattern or Template or anything at all really.
That said, I think I'd look at the Factory Pattern. The idea is that at
the highest level, you pass the file you want to read to the factory and
the factory figures out all the details.
File f = ...
MyParser parser = MyParser.factory( f );
Next, you might have different criteria for each file. What the
extension is, what magic bytes it has, in a pinch you might have to read
the file and look for a few different constructs to figure things out.
Then you want to instantiate a parser based on what you figured out.
So I see two types there. The first where do mach the file types is
maybe called a FileTypeCriteria, and the second is a FileParser. I'd
use both Strategy and Template for those, as you want a good API like
Template but you also might want to replace each individually and also
modify each with out affecting other code.
So the factory itself might be involved in just matching
FileTypeCriteria to FileParsers, with the real work delegated to a
FileParser, which maybe ought to parse a Stream rather than a file, now
that I think about it.
You'd have to init the factory with both FileTypeCriteria and FileParsers:
FileTypeCriteria criteria = ...
FileParser parser = ...
MyParser.addParser( criteria, parser );
Then you're off to the races, just make the criteria and parsers that
you need, and let the factory worry about binding them and serving them
to users.
I think a simple criteria could be implemented just from file names
something like this:
class FileNameCriteria implements FileTypeCriteria {
private final Pattern pattern;
public FileNameCriteria( String pattern ) {
pattern = Pattern.compile( pattern );
}
public boolean matchers( File f ) {
return pattern.matcher( f.getName() ).matches();
}
}
Then you could just make a new criteria for, say, HTML files something
like this:
new FileNameCriteria( "*.html^" );
and any other extensions similarly. Code not compiled or tested! Good
luck.