Search code examples
javaconfigurationindirectionmodularization

Design of a general-purpose handler class with swappable handler code?


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 ?


Solution

  • 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.