go 中的继承与多态

继承

package main

import (
	"fmt"
)


type Father struct {
	name string
	level int
}

func (*Father) Eat(){
	fmt.Println("我是父类的 eat")
}

func (*Father) Food(){
	fmt.Println("我是父类的 food")
}

type Son struct {
	Father
	work string
}

func (*Son) Eat(){
	fmt.Println("我是子类的 eat")
}

func (*Son) Rice(){
	fmt.Println("我是子类的 rice")
}


func main() {
	f := Father{"张三", 1}
	f.Eat() // 我是父类的 eat
	f.Food() // 我是父类的 food

	s := Son{f, "美食家"}
	s.Eat() //我是子类的 eat
	s.Rice() //我是子类的 rice
	
}

多态

package main

import (
	"fmt"
)

// 定义一个动物的接口
type Animal interface {
	Sleep()
	GetName() string
	GetColor() string
}

// 定义一个结构体 猫
type Cat struct {
	name string
}

// 定义一个结构体 狗
type Dog struct {
	name string
}


func (*Dog) Sleep() {
	fmt.Println("这只狗在睡觉。。。。。。")
}

func (this *Dog) GetName() string {
	return this.name
}

func (this *Dog) GetColor() string {
	return "黑色"
}


func (*Cat) Sleep() {
	fmt.Println("这只猫在睡觉。。。。。。")
}

func (this *Cat) GetName() string {
	return this.name
}

func (this *Cat) GetColor() string {
	return "百色"
}

func ShowAnimal(animal Animal) {
	animal.Sleep()
	fmt.Println("color: ", animal.GetColor())
	fmt.Println("name: ", animal.GetName())

}

func main() {
	c := Cat{"小白"}
	d := Dog{"小黑"}

	ShowAnimal(&c)
	ShowAnimal(&d)

	
}

例子

package main

import "fmt"


type Builder interface {
	Build()
}

type Director struct {
	builder Builder
}


func (d *Director) Construct(){
	d.builder.Build()
}

func NewDirector(builder Builder) Director {
	return Director{builder:builder}
}



type ConcreteBuilder struct {
	built bool
}

func (b *ConcreteBuilder) Build() {
	fmt.Println("我被调用了。。。。")
	b.built = true
}

func main() {
	cb := ConcreteBuilder{false}
	d := NewDirector(&cb)
	d.Construct()

	println("built is ", cb.built)


	/*
	我被调用了。。。。
	true
	*/
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值