当前位置:   article > 正文

golang接口的组合_golang的接口组合

golang的接口组合

一个接口A里写了另一个接口B, 代表的是接口的组合。在面向对象语义里,类似接口A同时继承了接口B和接口C.

下面写一个小栗子,车能地上跑,船能水上游,而水陆两栖作战车可以同时做到,还有作战能力。vn18型作战车是一种水陆两栖作战车。

使用接口组合逻辑,车是一个接口,船是一个接口,水陆两栖作战车有车和船的接口方法,同时定义了开火接口。

vn18作战车只需要实现水陆两栖作战车接口即可获得所有能力。


import "fmt"

// Vehicle 车辆
type Vehicle interface {
	run()
}

// Boat 船
type Boat interface {
	swim()
}

// Amphibious 水陆两栖
type Amphibious interface {
	Vehicle
	Boat
	fire()
}
// VN18AmphibiousVehicle vn18型步兵水陆两栖战车
type VN18AmphibiousVehicle struct {
	FireRating int // 射速
	Calibre int  // 口径
}

func (v VN18AmphibiousVehicle) fire()  {
	fmt.Println("AmphibiousVehicle fire: ",v.FireRating,"/",v.Calibre)
}

func (v VN18AmphibiousVehicle) run(){
	fmt.Println("AmphibiousVehicle fire")
}
func (v VN18AmphibiousVehicle) swim() {
	fmt.Println("AmphibiousVehicle swim")
}



func main()  {
	c:=&VN18AmphibiousVehicle{
		FireRating: 1,
		Calibre: 2,
	}
	c.fire()
	c.run()
	c.swim()
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/907790
推荐阅读
相关标签
  

闽ICP备14008679号