4-6 面向对象综合练习

package main

import (
    "fmt"
    "math/rand"
    "time"
)

type Animals interface {
    Live()
    Godie()
}
type Bird struct {
}

func (b *Bird) Live() {
    fmt.Println("一只鸟儿在飞翔")
}
func (b *Bird) Godie() {
    fmt.Println("一只鸟儿死翘翘")
}

type Fish struct {
}

func (f *Fish) Live() {
    fmt.Println("一只鱼儿在游泳")
}
func (f *Fish) Godie() {
    fmt.Println("一只鱼儿死翘翘")
}

type Beast struct {
}

func (b *Beast) Live() {
    fmt.Println("一只野兽在打滚")
}
func (b *Beast) Godie() {
    fmt.Println("一只野兽死翘翘")
}

func (b *Beast) Run() {
    fmt.Println("一个野兽在奔跑")
}
func (b *Beast) Hunt() {
    fmt.Println("一个野兽在捕食")
}

type tiger struct {
    Beast
}

func (t *tiger) Live() {
    fmt.Println("本王在巡视领地")
}

func (t *tiger) Godie() {
    fmt.Println("大猫也有godie的一天")
}

func (t *tiger) Run() {
    fmt.Println("本王在奔跑")
}
func (t *tiger) Hunt() {
    fmt.Println("本王在捕食")
}

type human struct {
    Beast
}

func (h *human) Live() {
    fmt.Println("广东人在工作")
}

func (h *human) Godie() {
    fmt.Println("人去世了")
}

func (h *human) Run() {
    fmt.Println("广东人在跑步")
}
func (h *human) Hunt() {
    fmt.Println("广东人在吃饭")
}

func main() {
    bird := Bird{}
    fish := Fish{}
    beast := Beast{}
    t := tiger{beast}
    h := human{beast}

    animals := make([]Animals, 0)
    animals = append(animals, &bird, &fish, &beast, &t, &h)
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    rand := r.Intn(7)
    fmt.Println(rand)

    if rand > 0 && rand < 6 {
        for _, animal := range animals {
            animal.Live()
        }
    } else {
        for _, animal := range animals {

            //使用第一种类型断言
            //switch animal.(type) {
            //case *human:
            //    //父类转子类
            //    //animal使用human的方法
            //    animal.(*human).Hunt()
            //case *Beast:
            //    //animal使用beast的方法
            //    animal.(*Beast).Run()
            //default:
            //    animal.Godie()
            //}

            //第二种类型断言的方法
            if human,ok := animal.(*human);ok {
                human.Hunt()
            }else if beast,ok:=animal.(*Beast);ok{
                beast.Hunt()
            }else {
                animal.Godie()
            }
        }
    }


}

 

posted @ 2019-06-27 14:52  pad+  阅读(165)  评论(0编辑  收藏  举报