Golang 使用接口的多态性

多态这个词意味着有多种形式。或者换句话说,我们可以将多态性定义为一条信息能够以多种形式显示。或者在技术术语中,多态性意味着相同的方法名称(但签名不同)被用于不同的类型。例如,一个女人在同一时间可以有不同的特征。像母亲、妻子、姐妹、雇员等等。所以同一个人在不同的情况下拥有不同的行为。这就是所谓的多态性。
在Go语言中,我们不能借助类来实现多态性,因为Go语言不支持类,但可以通过接口来实现。我们已经知道,接口在Go语言中是隐式实现的。因此,当我们创建了一个接口,而其他类型想要实现该接口时,这些类型就会在接口中定义的方法的帮助下使用该接口,而不知道其类型。在一个接口中,一个接口类型的变量可以包含任何实现该接口的值。这一属性有助于接口在Go语言中实现多态性。让我们借助于一个例子来讨论一下。

例子

// Go program to illustrate the concept
// of polymorphism using interfaces
package main
  
import "fmt"
  
// Interface
type employee interface {
    develop() int
    name() string
}
  
// Structure 1
type team1 struct {
    totalapp_1 int
    name_1     string
}
  
// Methods of employee interface are
// implemented by the team1 structure
func (t1 team1) develop() int {
    return t1.totalapp_1
}
  
func (t1 team1) name() string {
    return t1.name_1
}
  
// Structure 2
type team2 struct {
    totalapp_2 int
    name_2     string
}
  
// Methods of employee interface are
// implemented by the team2 structure
func (t2 team2) develop() int {
    return t2.totalapp_2
}
  
func (t2 team2) name() string {
    return t2.name_2
}
  
func finaldevelop(i []employee) {
  
    totalproject := 0
    for _, ele := range i {
  
        fmt.Printf("\nProject environment = %s\n ", ele.name())
        fmt.Printf("Total number of project %d\n ", ele.develop())
        totalproject += ele.develop()
    }
    fmt.Printf("\nTotal projects completed by "+
        "the company = %d", totalproject)
}
  
// Main function
func main() {
  
    res1 := team1{totalapp_1: 20,
        name_1: "Android"}
  
    res2 := team2{totalapp_2: 35,
        name_2: "IOS"}
  
    final := []employee{res1, res2}
    finaldevelop(final)
  
}

输出

Project environment = Android
 Total number of project 20

Project environment = IOS
 Total number of project 35

Total projects completed by the company = 55

解释: 在上面的例子中,我们有一个接口名称作为雇员。这个接口包含两个方法,即develop()和name()方法,在这里,develop()方法返回项目的总数,name()方法返回它们被开发的环境名称。

现在我们有两个结构,即team1,和team2。两个结构都包含两个字段,即totalapp_1 int , name_1 string , totalapp_2 int , and name_2 string 。现在,这些结构(即team1和team2)正在实现雇员接口的方法。

之后,我们创建一个名为finaldevelop()的函数,返回公司开发的项目总数。它接受一个雇员界面的片断作为参数,通过迭代片断并在其中的每个元素上调用develop()方法来计算公司开发的项目总数。它还通过调用name()方法来显示项目的环境。根据雇员接口的具体类型,不同的develop()和name()方法将被调用。所以,我们在finaldevelop()函数中实现了多态性。

如果你在这个程序中加入另一个实现雇员接口的团队,这个finaldevelop()函数将计算出公司开发的项目总数,而不会因为多态性而有任何变化。