Design pattern for rendering a business object

Discussions

General J2EE: Design pattern for rendering a business object

  1. I'd like to render a business object in different formats.. for example: HTML, XML, Text, etc. I'm curious what design pattern would be best for this. I know I can put methods in my business object:

    String renderAsXML();
    String renderAsHTML();
    String renderAsText();

    but I think there is a better way. One idea I had is to have a generic render method:

    String render(IRenderer r) {
      r.render();
    }

    but the IRenderer object must know about my business object. This gives me:

    String render(IMailRenderer r) {
      r.render(this);
    }

    Then my renderer implemenation:

    class MailXMLRenderer implements IRenderer {
      String render(Mail m) {
        StringBuffer sb = new StringBuffer();
        // build up a StringBuffer using m's properties
        // ...
        return sb;
      }
    }

    Is this the "Visitor" pattern? Is this a good idea? Any better ideas??

    Thanks,
    Michael
  2. Why not convert your object model to XML, and render it various ways using XSL? This way you only need to write renderAsXML() in Java code.

    Failing that, I would create something like this:

    1) A Renderer interface like yours:

    interface Renderer {
      String render(Object renderee);
    }

    2) A RendererFactory with the following method:

    Renderer getRenderer(Class renderee, String environment);

    3) A configuration file that maps class/environment to Renderer subclasses, used by the RendererFactory to determine the correct renderer subclass.

    com.domain.Example:text=com.domain.renderers.ExampleTextRenderer
    com.domain.Example:html=com.domain.renderers.ExampleHtmlRenderer
    ...

    4) A set of "generic" renderers that use reflection, to use if there is no class-specific renderer:

    GenericHTMLRender, GenericTextRender, GenericXMLRender ...
  3. Hi,
    Accoridng to MVC your bussiness object is teh Model. the View could be comoposed of several renderers (HTML, XML, etc.). The Controller should decide the view to be used in a particular request.
    Best regards, Mircea