Categories

Neat trick : a Factory embedded in the interface of the object it builds

I’ve seen this trick performed by IntelliJ when using their integration with Google Web Toolkit. Usually, you’ve got an API defined as an interface, and you need a factory to build an implementation of the interface. The factory uses some configuration information to choose an implementation :

public interface MyService {
     // ...
}

public class MyServiceFactory {
   public static MyService getMyService() {
         // ... load configuration and return an instance of a class implementing MyService
   }
}

// Usage example :
MyService serviceP = MyServiceFactory.getMyService();

Of course there are hundreds of variations to this pattern, with or without singletons for the factory etc. The trick I’ve seen performed by IntelliJ relies on the fact that you can define an inner class in an interface :

public interface MyService {
     // ...
     public static class Factory {
         public static MyService getMyService() {
             // ... as before...
         }
     }
}

// Usage example :
MyService serviceP = MyService.Factory.getMyService();

It doesn’t change much but it feels cleaner like that ; of course you can’t implement factories of factories of factories, if that’s your pleasure, but to me it’s way simpler to have the factory defined right in the interface.