Aspire

go中如何实现多态

发布时间:6年前热度: 3303 ℃评论数:

package main 

import "fmt"

//import "reflect"


type Animal interface {

    Sleep()

    Age() int

    Type() string

}


type Cat struct {

    MaxAge int

}

func (this *Cat) Sleep() {

    fmt.Println("Cat need sleep")

}

func (this *Cat) Age() int {

    return this.MaxAge

}

func (this *Cat) Type() string {

    return "Cat"

}




type Dog struct {

    MaxAge int

}

func (this *Dog) Sleep() {

    fmt.Println("Dog need sleep")

}

func (this *Dog) Age() int {

    return this.MaxAge

}

func (this *Dog) Type() string {

    return "Dog"

}


func Factory(name string) Animal {

    switch name {

    case "dog":

        return &Dog{MaxAge: 20}

    case "cat":

        return &Cat{MaxAge: 10}

    default:

        panic("No such animal")

    }

}


func main() {

    animal := Factory("cat")

    animal.Sleep()

    fmt.Printf("%s max age is: %d", animal.Type(), animal.Age())

}


源码安装、技术讨论、二次开发等联系微信:

go中如何实现多态

栏目导航

  1. PHP
  2. Go
  3. Mysql
  4. Linux
  5. 前端
  6. 杂谈

手机扫码访问