I am creating a program where I have objects called “hierarchies”, which is little more than a list of lists with strings (ArrayList<ArrayList<String>>) with appropriate getters.
The user should be able to select the representation/formatting of these hierarchies – e.g. whether the hierarchy [1,2,3,4] should be represented as {1,2,3,4} or (1-4) or whatever, before it is written to a file.
Is there a clever/standard way to do this kind of separation of data and formatting? I am thinking of creating a “FormattedHierarchy”-object which merely consists of a Hierarchy-object and a Formatting-object, but I don’t know if this is a good design choice or not.
Thanks for any pointers/tips/answers.
The worst thing you can do is coupling your hierarchy data representation with formatting. The hierarchy class should not know anything about formatting. My advice is to create a separate interface
HierarchyFormatterwith several different implementations.I think code is worth thousand words:
This is called a strategy design pattern. If some code needs to format your hierarchy, just pass an instance of
HierarchyFormatter– any instance.If you want to permanently bind hierarchy with some formatting, make your formatter stateful:
Every time you create a formatter, you encapsulate the hierarchy class inside it.