如何在Go中保留工厂功能?

时间:2011-05-08 06:38:02

标签: go

我正在尝试保存一个函数,该函数将返回在结构中实现特定接口的类型的新实例。这是一个精简的例子:

package main

type Adder interface {
    Add(Adder)
    Val() int
}

type NewAdder func() Adder

type number int

type NewHolder struct {
    newFunc NewAdder
}

func (me *number)Add(it Adder) {
    *me += number(it.Val())
}

func (me *number)Val() int {
    return int(*me)
}

func newAdder() *number {
    return (*number)(new(int))
}

func main() {
    var holder NewHolder
    holder.newFunc = NewAdder(newAdder)
}

当我尝试编译它时,它会显示cannot convert newAdder (type func() *number) to type NewAdder。那么实现目标的方式是什么?

这是我正在尝试做的Python示例,仅供参考:

class NewStuffMaker(object):
    def __init__(self, new):
        self.new = new

def make_new():
    return []
obj = NewStuffMaker(make_new)
new_lst = obj.new()

理想情况下,我希望能够在切片中保存一堆这些函数(或包含函数和其他数据的结构)。这是不合理的事吗?

1 个答案:

答案 0 :(得分:1)

package main

type Adder interface {
    Add(Adder)
    Val() int
}

type FuncAdder func() Adder

type Holder struct {
    FuncAdder
    SomeOtherData string
}

type number int

func (n *number) Add(a Adder) {
    *n += number(a.Val())
}

func (n *number) Val() int {
    return int(*n)
}

func NumberAdder() Adder {
    return Adder(new(number))
}

func main() {
    var holders []Holder
    var holder Holder
    holder.FuncAdder = NumberAdder
    holder.SomeOtherData = "SomeOtherData"
    holders = append(holders, holder)
}