views:

122

answers:

4
+4  Q: 

Pattern Question

Just starting to learn patterns. Here's a simple question I have.

I have an object Report that contains Pages, each of which contains various ReportElements (Table, Paragraph, Image) and so on. Suppose I want to create an infrastructure for taking a Report and spitting various representations of this Report such as an RTF-formatted document, a TeX-formatted document, an HTML document, etc.

Which design pattern am I looking for here?

+10  A: 

Strategy I believe.

You could create an RTFReportGenerator, a HtmlReportGenerator, etc... which all implement the same 'IReportGenerator' interface, but each concrete class implements the 'WriteReport(Report r)' method in a different way.

Frederik Gheysels
Each individual "Generator" may be a Builder. http://en.wikipedia.org/wiki/Builder_pattern
S.Lott
Hmm, I believe the 'object' (Report) has already been created; the 'Generator' should just 'generate' a file that contains an RTF / HTML / ... representation of the Report instance that has been given.
Frederik Gheysels
"The Generator should..." Agreed -- the point is that patterns nest and overlap. There's rarely a single pattern for this kind of thing.
S.Lott
A: 

Don't search for concrete pattern. Many patterns have the same structure but different aims. And anyhow you always have to make some changes in pattern to use it in your concrete case. After learning patterns you'll be able to think correctly about objects and their relationship.

You can use strategies for different representations, you can use builder for creating you Report.

And you can also use something simpler. Like combination of delegation and inheritance (for me it's the best solution of your problem). Just create ierarchy of Representations (BasicView<|-- RTFView, TextView...) and pass Report to BasicView constructor. Let different views provide different data transformation of original Report.

Roman
+1  A: 

For a group of organised objects the Visitor pattern is also applicable. This deals a little bit better with traversal of structures of objects, depending on your needs you can use it for other tasks that need to deal with your reports as a group.

Harald Scheirich
A: 

I would probably use the Composite pattern to represent the tree of report elements, and Visitor (as Harald said) to turn the report object into a specific concrete representation.

Drew Hall