3 Replies Latest reply on Nov 1, 2010 12:45 PM by Hugh Lomas

    Dynamic proxies as decorators and architecture advice

    Hugh Lomas Newbie

      I am attempting to create a system in which business entities such as a Person or a Company have a number of roles/types/responsibilities.

      For example, a Company may be a Vendor, or it may be a Customer, or it may be both a Vendor and Customer. Inheritance is obviously a mess when given a large number of roles.

      Interfaces also seem inadequate for this:

      public class Company implements IVendor, ICustomer{

      The above would mean that instances of Company that were only customers would also have a Vendor interface.

      After searching for some solutions I found dynamic proxies, which to my untrained eye appear to be capable of solving this problem.

      However according to Seam in Action:

      Why doesn’t Seam support JDK dynamic proxies? A JDK dynamic proxy is a dynamically generated class that implements a set of inter- faces specified at runtime. A dynamic proxy class can’t be cast to the target bean’s class, nor does it provide access to the target bean (i.e., the proxied object). The proxy just happens to implement the same interface(s) as the target bean. Cglib prox- ies, on the other hand, can be treated more or less like the target bean itself. Cglib creates a new concrete class on the fly that is a subclass (in other words, a class that extends the target bean’s class). Because Seam needs direct access to the tar- get bean to expose it as a Seam component, it’s mandatory that the target bean be enhanced using Cglib rather than act through a JDK dynamic proxy.

      From continued searching it appears that Javassist is the library of choice for Seam rather than Cglib.

      I am under the assumption that given a Company object I should be able to use a dynamic proxy to effectively decorate it with Vendor and Customer methods and member variables. In other words, a Company object should be able to act as a Company, a Vendor, a Customer, and an arbitrary selection of other roles.

      My searches for implementation examples of this type of structure have been fruitless, and I am not entirely certain whether or not I am approaching the problem completely incorrectly.

      Does anyone know of any good examples of accomplishing the above, or any other solutions that might be more apt to address the problem?