I have the following pattern, which I would like to implement using some kind of generic programming, but I do not see how I can do it.
I have an interface I containing many methods with different signatures. Each method has a return type of some class type and any implementation should return null on failure, or a concrete object on success.
Now I have a concrete implementation A of I, and a decorator class D of A. For each method
T m(T1 p1, ..., Tn pn)
defined by the interface I, the implementation of m in D follows a fixed pattern:
class D
{
private A impl = ...;
...
T D.m(t1 p1, t2 p2, ..., tn pn)
{
init();
T result = impl.m(p1, ..., pn);
if (result != null)
successCode();
else
failureCode();
return result;
}
}
The calling code uses the decorator as follows:
I instance = DecoratorFactory.createIDecorator();
T r = instance.m(p1, ..., pn);
Question: Is there a way to implement this kind of decorator in a generic way (without writing the same boilerplate for each method)? Can this be done in Java?
If it is not possible to implement this pattern in Java, is there an elegant way to implement it in another language?