Given a complex object hierarchy, which luckily contains no cyclic references, how do I implement serialization with support for various formats? I’m not here to discuss an actual implementation. Instead, I’m looking for hints on design patterns which might come in handy.
To be a little more precise: I’m using Ruby and I want to parse XML and JSON data to build up a complex object hierarchy. Furthermore, it should be possible to serialize this hierarchy to JSON, XML, and possibly HTML.
Can I utilize the Builder pattern for this? In any of the mentioned cases, I have some sort of structured data – either in memory or textual – which I want to use to build up something else.
I think it would be nice to separate the serialization logic from the actual business logic, so that I can easily support multiple XML formats later on.
I ended up creating a solution which is based on the Builder and the Strategy pattern. I’m using the Builder pattern to extract parsing and building logic into there own classes. This allows me to easily add new parsers and builders, respectively. I’m using the Strategy pattern to implement the individual parsing and building logic, because this logic depends on my input and output format.
The figure below shows a UML diagram of my solution.
The listing below shows my Ruby implementation. The implementation is somewhat trivial because the object I’m building is fairly simple. For those of you who think that this code is bloated and Java-ish, I think this is actually good design. I admit, in such a trivial case I could have just build the construction methods directly into my business object. However, I’m not constructing fruits in my other application, but fairly complex objects instead, so separating parsing, building, and business logic seems like a good idea.