Dave Arkell
Dave Arkell

Reputation: 3980

Pattern for saving and writing to different file formats

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.

Upvotes: 5

Views: 1945

Answers (3)

Ricardo Amores
Ricardo Amores

Reputation: 4687

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.

Edit: Link to the original Memento pattern article using google cache

Upvotes: 2

Patrick Huizinga
Patrick Huizinga

Reputation: 1340

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.

Upvotes: 0

erlando
erlando

Reputation: 6756

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

Upvotes: 1

Related Questions