Go 语言类型与函数深度解析
1. 工厂方法
在 Go 语言中,好的工厂方法设计很重要。例如,定义 IntegerList 接口及相关工厂方法:
type IntegerList interface {
Len() int
GetAt(index int) int
SetAt(index int, v int)
}
func makeIntegerList() IntegerList { ... }
工厂方法通常应返回指针,像 NewIntegerList 这样的方法:
func NewIntegerList() *IntegerList { ... }
它能返回实现了 IntegerList 接口的任何类型。也可以有类似 MakeIntegerList 的方法:
func MakeIntegerList() IntegerList {
return *NewIntegerList()
}
要注意,不传递和返回指针时,值会被复制,这可能增加开销并导致行为问题。工厂方法很少有接收者参数,但类似 Clone 这样基于复制或原型的方法除外:
f
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



