For converting a Java object model into XML I am using the following design:
For different types of objects (e.g. primitive types, collections, null, etc.) I define each its own converter, which acts appropriate with respect to the given type. This way it can easily extended without adding code to a huge if-else-then construct.
The converters are chosen by a method which tests whether the object is convertable at all and by using a priority ordering. The priority ordering is important so let’s say a List is not converted by the POJO converter, even though it is convertable as such it would be more appropriate to use the collection converter.
What design pattern is that?
I can only think of a similarity to the command pattern.
Well, you can start by trying to categorize the thing you want to do (output an XML file, convert something to something). The design patterns fall into three categories;
In this case you have two types of classes, an xml writer and some converters. The xml writer is basically a builder (it creates a file)
Now, the actual conversion of a class to xml is done by a few classes. You mention you have a method which tests the classes and directs them to a specific converter. This class can be argued to create a new instance of something, so it falls into the creational patterns.
There are three types of patterns that would be suitable IMO.
Either one is appropriate according to me. The builder pattern is appropriate since the implementation is sort of like
i.e. you give the class something and you get a result.
The factory pattern is appropriate since you defer instantiation to some other class (your redirect method you spoke of)
In either case the actual type of the returned item is not important. It depends a little on where you want to "define the pattern". Is it in the method where you switch types, or in the actual creation/converter class.
Then again, I’m no expert in the case.