Design pattern for multiple output formats

后端 未结 7 1997
清酒与你
清酒与你 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:26

    If you need to implement file formatting and save/load from outside of the class, then you can only do it with data that is publicly available. If saving/loading needs to deal with non-public data, if reloading the class cannot reconstruct the original non-public data from public data, then either the class itself or friends of that class must be involved. There's not really a way around that.

    The most you might be able to do is to make it easier to write new types, with a friend template. For example:

    class DataType
    {
    ...
    private:
        template friend void SaveFile(const DataType *, ofstream&);
    };
    

    The format template type would be empty types. So if you have formatA and formatB, you would have empty structs:

    struct FormatA {};
    struct FormatB {};
    

    Then, all you need to do is write specialized versions of SaveFile for those formats:

    template<> void SaveFile(const DataType *, ofstream&);
    template<> void SaveFile(const DataType *, ofstream&);
    

    They will automatically be friends of DataType.

提交回复
热议问题