Java – Generic Decorator Implementation

java

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?

Best Answer

What you are probably looking for is called Aspect Oriented Programming. It works with the Proxy-Pattern, which is just what you need.

You can create a dynamic proxy for each object and tell that proxy to intercept said calls and perform your logic. All you need is one dynamic proxy class that contains your interception logic. It will wrap around any object you give it and try to perform your logic.

Start to look here:

I haven't read that articles, though. Just browse the web for the implementation/library that fits your needs best.

You might also want to check out AspectJ.

Related Topic