2

我是golang的新手。我需要设计一个函数来根据输入创建不同类型的对象。但是我没有弄清楚如何设计界面。这是我的代码:

package main

import (
    "fmt"
)

type AA struct{
    name string
}

func (this *AA) say(){
    fmt.Println("==========>AA")
}
type BB struct{
    *AA
    age int
}
func (this *BB) say(){
    fmt.Println("==========>BB")
}

func ObjectFactory(type int) *AA {
    if type ==1 {
        return new(AA)
    }else{
        return new(BB)
    }
}

func main() {
    obj1 := ObjectFactory(0)
    obj1.say()
    obj2 := ObjectFactory(0)
    obj2.say()
}

无论我要求 ObjectFactory 返回 *AA 还是 interface{},编译器都会告诉我错误。我怎样才能让它工作?

4

1 回答 1

7

首先,type在 go 中不允许将其用作变量名(请参阅规范)。那是你的第一个问题。

对象工厂的返回类型是*AA。这意味着它只能返回*AA类型的变量,导致BB类型的返回失败。按照规范中的定义,go 没有类型继承,只有结构嵌入。

如果您创建一个名为 sayer 的接口,您可以在 ObjectFactory 函数中使用它而不是 *AA。

type sayer interface {
    say()
}

您可能希望在尝试获得多个分派时使用此接口(如下面的代码所示(参见play.golang.org)。

试试这个代码:

package main

import (
    "fmt"
)

type sayer interface {
    say()
}

type AA struct{
    name string
}

func (this *AA) say(){
    fmt.Println("==========>AA")
}
type BB struct{
    *AA
    age int
}
func (this *BB) say(){
    fmt.Println("==========>BB")
}

func ObjectFactory(typeNum int) sayer {
    if typeNum ==1 {
        return new(AA)
    }else{
        return new(BB)
    }
}

func main() {
    obj1 := ObjectFactory(1)
    obj1.say()
    obj2 := ObjectFactory(0)
    obj2.say()
}
于 2013-11-15T07:21:14.780 回答