You can use the fact that interfaces allow nested classes (automatically public static) to support the standard implementation of interface methods encapsulated in the interface itself. That is, move the BusinessLogic class of example Alex B inside the interface.
This is similar to the way Scala generates JVM code for tags, as described here How are Scala compiled into Java bytecode?
The example will look like this:
interface BusinessLogicInterface { void method0(); class DefaultImpl { private DefaultImpl() { } public static void method1(BusinessLogicInterface self) { ... } public static void method2(BusinessLogicInterface self) { ... } } void method1(); void method2(); } class User extends OtherClass implements BusinessLogicInterface { @Override void method0() { ... } @Override void method1() { BusinessLogic.defaultImpl.method1(this); } @Override void method2() { BusinessLogic.defaultImpl.method2(this); } }
Please note that we pass the object of the interface type as the parameter "self". This means that business logic can use other abstract methods (method0). This can be very useful for creating a feature with abstract methods that are all orthogonal to each other and utility βextensionβ methods that can be implemented in terms of these orthogonal methods.
The disadvantage is that each interface must copy / paste the template delegation code. Another commonly used pattern in Java without this drawback (but with less connectivity and fewer OO methods for calling methods) is to create a plural name class as an interface containing static methods, which is used in the Collections utility class.
Henno Vermeulen May 2 '13 at 11:49 am
source share