多种输出格式的设计模式 [英] Design pattern for multiple output formats

查看:101
本文介绍了多种输出格式的设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类结构,该结构表示(内部)我想输出到文件中的数据.

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 can manage itself and stop things going awry.

然后我希望将此数据输出为多种文件格式.我可以做类似的事情

I then want this data to be output into a number of file formats. I could do something like

savefile_formatA(DataClass* pDataClass, ofstream& fout);
savefile_formatB(DataClass* pDataClass, ofstream& fout);

除了函数需要查看DataClass的私有成员变量外.我当然可以只使savefile_formatXYZ()朋友功能,但然后我需要为每种不同的格式添加一个朋友声明.

except that the functions need to then see the private member variables of DataClass. I could of course just make savefile_formatXYZ() friend functions but then I would need to add a friend declaration for every different format.

是否存在解决此类问题的标准设计模式?您将如何解决这个问题?

Is there a standard design pattern for solving this kind of thing? How would you solve this problem?

谢谢!

推荐答案

根据数据类的复杂性,您可能希望使用Visitor模式.如果您有某种嵌套的数据结构,那么访问者很可能就是您所需要的.

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() );

然后数据类具有方法

  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.

这篇关于多种输出格式的设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆