views:

230

answers:

3

Is there a pattern that is good to use when saving and loading different file formats?

For example, I have a complicated class hierarchy for the document, but I want to support a few different file formats.

I thought about the Strategy pattern, but I'm not convinced because of the need to access every part of the object in order to save and load it.

+1  A: 

You might want to take a look at the Builder pattern. GoF page 97..

erlando
A: 

How about (something based on) the Template method pattern?

One superclass knows how to rip apart the class hierarchy, but relies on its subclasses to actually do something useful with it.

Patrick Huizinga
+1  A: 

You could use a Visitor Pattern, it allows to iterate over your hierachy doing different operations depending of the node the Visitor is currently processing.

Bad news: you probably need to add at least a virtual method at the top of the hierarchy, and maybe redefine it in some derived classes, and the visitor still access the data of the nodes, but you decouple the file format, as different visitors implementations can write the data gathered in different ways.

Take a look also at the memento pattern if hiding the class hierachy data is a must. This article could also be helpful.

Ricky AH