Friday, May 29, 2009

Decorator/Wrapper pattern

I started writing code using Document class from w3c.org.

Pretty soon it seemed like I was writing a lot of methods which would logically go into an extension of the Document implementation.

So I tried extending XMLDocument (Oracle's implementation of this) in order to have a better place to put these methods.

But the way I was producing this document I was using DocumentBuilder method that parses a file, and returns a Document.

So in my code I could not think of a way to call this, parse method and get a XMLDocument and then cast it to my class so I could use my new methods.

SO: Here is what I did. I created a decorator (wrapper) class which implements the Document interface, and then passed in the returned document from the parse method to the constructor to my new class. Then all I had to do was to implement every method in the Document and Node interface (Document interface extends Node interface).

Only trouble here is there were a lot of methods in these interfaces, and other than write my own program to generate the default wrapper methods I had to hand-type them all in. Pretty tedious and generates a gob of code.

Vik Kumar from Oracle Corporation seemed to agree that this extra code was necessary to "extend" implementations of the Document interface.

Someone else mentioned on the internet that IntelliJ IDEA had a wizard to generate this decorator pattern class, but I downloaded a trial and could not find such a wizard.

No comments: