Go与Java类型对比:数组、切片、映射和函数的深入剖析
1. 工厂方法
在Go语言中,工厂方法是创建对象的一种有效方式。例如,定义一个 IntegerList 接口及其工厂方法:
type IntegerList interface {
Len() int
GetAt(index int) int
SetAt(index int, v int)
}
func makeIntegerList() IntegerList { ... }
工厂方法通常应返回指针,不过像 Make<typename> 这样的替代工厂名也是允许的,并且在合适的情况下可以返回实例而非指针。例如:
func NewIntegerList() *IntegerList { ... }
func MakeIntegerList() IntegerList {
return *NewIntegerList()
}
需要注意的是,在不传递和返回指针时,值会被复制进出函数,这可能会增加开销并导致一些行为问题。此外,工厂方法很少有接收者参数,但像 Copy 或 Clone 这样基于复制或原型的方法是例外:
func (il *IntegerList) Clone() *IntegerList { ... }
<
超级会员免费看
订阅专栏 解锁全文
63

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



