gpt4 book ai didi

design-patterns - 使用哪种设计模式将不同类型的对象流存储到磁盘中?

转载 作者:IT王子 更新时间:2023-10-29 01:06:37 29 4
gpt4 key购买 nike

考虑一个将不同类型的对象流保存到磁盘的函数:

func Save(fill func(c chan BaseType), file string) {}

此函数在整个代码中的使用方式如下:

// Here we've got different data structures data1, data2, ...
// that must be stored to disk
Save(
func(c chan BaseType) {
// SaveChildren1 generates objects of type Child1 based
// on the data1 data structure
SaveChildren1(c, data1)
},
filename1)

Save(
func(c chan BaseType) {
// SaveChildren2 generates objects of type Child2 based
// on the data2 data structure
SaveChildren2(c, data2)
},
filename2)

等等。有很多不同的子类型,每个都需要自己的生成器——函数 SaveChildren1、SaveChildren2 等。这些函数实际上用对象填充 channel 。

问题是您将如何重构这些“绑定(bind)器”——将 SaveChildren(2 个参数的函数)转换为 1 个参数的函数的函数?目前这段代码看起来不像是写得很好的 go-style 代码。

最佳答案

gob 包似乎是解决您问题的好方法。有一个很棒的article on the Go blog这解释了如何以及为什么。一个简短的摘录:

The gob package was designed with a number of goals in mind.

First, and most obvious, it had to be very easy to use. First, because Go has reflection, there is no need for a separate interface definition language or "protocol compiler". The data structure itself is all the package should need to figure out how to encode and decode it. On the other hand, this approach means that gobs will never work as well with other languages, but that's OK: gobs are unashamedly Go-centric.

Efficiency is also important. Textual representations, exemplified by XML and JSON, are too slow to put at the center of an efficient communications network. A binary encoding is necessary.

Gob streams must be self-describing. Each gob stream, read from the beginning, contains sufficient information that the entire stream can be parsed by an agent that knows nothing a priori about its contents. This property means that you will always be able to decode a gob stream stored in a file, even long after you've forgotten what data it represents.

文章的下方是一个示例,展示了它的易用性和通用性。

关于design-patterns - 使用哪种设计模式将不同类型的对象流存储到磁盘中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30041461/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com