I want to write a general-purpose handling class for files. This class is to load a specific handler instance depending on the type of file that's passed to it.

One of the methods inside would work like this (see comments):

public void doSomething( File ) {
// 1) Determine file type.
// 2) Use a lookup to see if an appropriate handler exists.
// 3) If a handler exists, use handler to do something with the file.
}

How could the main class be designed ?

P.S: I've been thinking of having Properties or an XML file being read in the constructor or a dedicated lookup method. There is also the idea of having the main class refer an interface into which a handler module could be loaded. Perhaps this corresponds with a pattern of some kind ?

有帮助吗?

解决方案

This looks like some kind of Abstract Factory Pattern.
You first need to define the 'contract' for your handler via some interface such as

public interface Handler {
 void handle(final File file);
}

You then need to define the different handlers; XMLHandler, PropertiesHandler, etc..
Now you need a Factory to give you a handler instance from a file extension (say), its interface may look like

public interface HandlerFactory {
  Handler newHandler(final String fileName);
}

Now you just need implementations for all that - for example the HandlerFactory could read extension->Class associations from a properties file or some such.

其他提示

There are a number of patterns that correspond to this, but this is a very c ommon task in OOP.

In Java, first determine the type of file. I will leave that to you.

Then use the ClassLoader to load and instantiate the relevant handler.

Typecast it, and go ahead and use it!

Dynamic Instantiation is a cool feature of Java, C# etc.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top