Java Decorator pattern example

Γιώργος Βαλοτάσιος 11/09/2011

Ok what the hell is the decorator pattern? Why do I need it?


I can not say that I am good explaining theory. I just read it and try to apply it where possible! After all practice and theory, theoretically are exact the same! So If you are intrested in theory, I thing that this article at Wikipedia can explain pretty well what it is all about. But if you are like me I do not know if you will remember what exactly is and where to use it if you haven't used it at least once!

A real example using the Decorator pattern

The funny thing is that I've been using this pattern a lot (even if I did not realize it from the first moment) and I'm pretty sure that many of you have. Where? Within every web application that uses the servlet directly. The scenario is that I want to make sure that when I use the getRemoteAddr() of a request I should always first check if there is an X-Forwarded-For header within the request and if so use that ip address. The solution is a custom HttpServletRequest. The servlet api gives us the tool in order not to have to write a lot of boilerplate code which is called HttpServletRequestWrapper. The class should look like the one below.

If you are also intrested in how to actually use it,that is with a Servlet filter:

Then all you have to do is to decorate a little bit more the first HttpServletRequest which is as easy as adding the line req = new XSSAwaareReq(req) before the return new XFFAwareReq(req); one letting the XFFAwareRequest untouchable and not breaking for example existing tests! Now you know that you've used the decorator pattern with in your web apps!