« Dummy’s guide to drawing raw images in Java 2D | Home | Java 7 Roundup (Oct 18th) »
Embedded factories
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:
and callers say:
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.

7 Comments
Jump to comment form | comments rss | trackback uri