Pure Danger Tech


navigation
home

Embedded factories

18 Oct 2007

I saw this post on needing static methods in an interface (for a factory method) and had a few thoughts.

The first thing it reminds me of is Stefan Schulz’s ideas on adding static contracts to Java as a way to solve this problem. A contract would basically be like an interface of static methods, which seems like something I really want to create about once a year for some reason.

For this particular case, I find this idiom (stolen blatantly from XMLBeans) works pretty well: [source:java]

public interface Blah {</p>

// methods for the interface

public static class Factory {

public static Blah newInstance() {

return new DefaultBlah();

}

}

}

[/source]

and callers say: [source:java]

Blah blah = Blah.Factory.newInstance();

[/source]

This prevents callers from tying directly to DefaultBlah, leaves the door open for more factory methods (which might do something fancier like dynamically loading an implementation based on a name) in the future, and prevents the extra source file for the factory (if not the factory class).

I used this style for about a year and found it worked pretty well. It does bind your interface to the default implementation, which I find mildly objectionable. In cases where there is an interface and just one implementation (you’re really creating the interface to allow injection, testing, mocking, etc) it works great.