Design pattern for multiple output formats

后端 未结 7 2017
清酒与你
清酒与你 2021-01-05 04:41

I have a class structure which represents (internally) the data I wish to output to a file.

Some of the member variables are private to the data class so that it ca

7条回答
  •  悲哀的现实
    2021-01-05 05:16

    Depending upon the complexity of your data class you may wish to use a Visitor pattern. If you have some kind of nested data structure then Visitor may well be what you need.

    If formatting is something relatively simple, for example you are producing variations on something such as a comma separated list then you can take an approach like this.

    Your formatter objects all implement an interface such as (pseudo code)

     IFormatter ( start(); addInt(name, value), addString(name, value) .... end() );
    

    then the data class has a method

      public void formatMyself( IFormatter formatter ) {
    
            formatter.start()
            formatter.addString("aField", myA);
            formatter.addInteger("bfield", myB);
            formatter.end();          
      }
    

    This makes the class being formatted responsible for the choice of data to be formatted, and the formatter responsible for the details of the format.

提交回复
热议问题