如何在不失去灵活性的情况下摆脱冗长的初始化
How to get rid of long initialization without losing flexibililty
考虑这个例子
Gabi::Herbs::Filesystem::FileReader filereader
{
Gabi::Herbs::Filesystem::FileIn
{Gabi::Herbs::Filesystem::Path(GABI_HERBS_STR("herbs/textio/test_utf8.txt")),0}
,0
};
Gabi::Herbs::IO::ReaderBuffering reader(filereader,128);
Gabi::Herbs::TextIO::Decoder decoder(reader,Gabi::Herbs::TextIO::ConverterUTF8::factory);
它是 C++,但它可以是任何支持 OOP 的语言。所以
- 使用路径抽象来区分文件路径和一般字符串
- 创建一个随机访问文件。这不会移动任何文件指针
- 使用 FileReader 读取文件 [FileIn 已通过引用计数复制构造]。 reader 将从文件开头开始零字节。
- 既然是文本文件,最好用buffered I/O。这减少了所需的系统调用数量。在这种情况下,它在每次调用时获取 128 个字节。
- 一个文本文件可以用许多不同的方式编码。创建一个尝试解码文件的解码器。
在这种情况下如何创建包装器,这样我就不需要创建三个对象和两个临时对象?可以使用合并 类,但会失去一些灵活性。
也许创建一个新的 class,像这样:
class FileReaderDecoder
{
Gabi::Herbs::Filesystem::FileReader filereader;
Gabi::Herbs::IO::ReaderBuffering reader;
Gabi::Herbs::TextIO::Decoder decoder;
public:
FileReaderDecoder(std::string file_name)
{/*Initialize the three member variables like you did in your own code*/}
//Add accessor functions here to get the data from the decoded file, e.g.:
std::string GetData(int start, int size);
}
然后呼叫减少到,例如
FileReaderDecoder file_rd_dec("herbs/textio/test_utf8.txt");
file_rd_dec.GetData(0, 16);
考虑这个例子
Gabi::Herbs::Filesystem::FileReader filereader
{
Gabi::Herbs::Filesystem::FileIn
{Gabi::Herbs::Filesystem::Path(GABI_HERBS_STR("herbs/textio/test_utf8.txt")),0}
,0
};
Gabi::Herbs::IO::ReaderBuffering reader(filereader,128);
Gabi::Herbs::TextIO::Decoder decoder(reader,Gabi::Herbs::TextIO::ConverterUTF8::factory);
它是 C++,但它可以是任何支持 OOP 的语言。所以
- 使用路径抽象来区分文件路径和一般字符串
- 创建一个随机访问文件。这不会移动任何文件指针
- 使用 FileReader 读取文件 [FileIn 已通过引用计数复制构造]。 reader 将从文件开头开始零字节。
- 既然是文本文件,最好用buffered I/O。这减少了所需的系统调用数量。在这种情况下,它在每次调用时获取 128 个字节。
- 一个文本文件可以用许多不同的方式编码。创建一个尝试解码文件的解码器。
在这种情况下如何创建包装器,这样我就不需要创建三个对象和两个临时对象?可以使用合并 类,但会失去一些灵活性。
也许创建一个新的 class,像这样:
class FileReaderDecoder
{
Gabi::Herbs::Filesystem::FileReader filereader;
Gabi::Herbs::IO::ReaderBuffering reader;
Gabi::Herbs::TextIO::Decoder decoder;
public:
FileReaderDecoder(std::string file_name)
{/*Initialize the three member variables like you did in your own code*/}
//Add accessor functions here to get the data from the decoded file, e.g.:
std::string GetData(int start, int size);
}
然后呼叫减少到,例如
FileReaderDecoder file_rd_dec("herbs/textio/test_utf8.txt");
file_rd_dec.GetData(0, 16);