本文實(shí)例講述了Go語(yǔ)言使用組合的方式實(shí)現(xiàn)多繼承的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
在大多數(shù)面向?qū)ο蟮木幊陶Z(yǔ)言中多繼承都是不支持的。因?yàn)樵诨赾lass的體系中,多繼承極大地增加了編譯器的復(fù)雜性。
Go語(yǔ)言使用組合的方式實(shí)現(xiàn)繼承,因此也可以很簡(jiǎn)單的實(shí)現(xiàn)多繼承。
復(fù)制代碼 代碼如下:
//使用組合的方式實(shí)現(xiàn)多繼承
type Phone struct{}
func (p *Phone) Call() string {
return "Ring Ring"
}
type Camera struct{}
func (c *Camera) TakeAPicture() string {
return "Click"
}
//多繼承
type CameraPhone struct {
Camera
Phone
}
func structTest0803() {
cp := new(CameraPhone)
fmt.Println("Our new CameraPhone exhibits multiple behaviors ...")
fmt.Println("It exhibits behavior of a Camera: ", cp.TakeAPicture())
fmt.Println("It works like a Phone too: ", cp.Call())
/*Output:
Our new CameraPhone exhibits multiple behaviors ...
It exhibits behavior of a Camera: Click
It works like a Phone too: Ring Ring
*/
}
希望本文所述對(duì)大家的Go語(yǔ)言程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- Golang正整數(shù)指定規(guī)則排序算法問(wèn)題分析
- Golang最大遞減數(shù)算法問(wèn)題分析
- Go語(yǔ)言展現(xiàn)快速排序算法全過(guò)程的思路及代碼示例
- 深入解析快速排序算法的原理及其Go語(yǔ)言版實(shí)現(xiàn)
- GO語(yǔ)言利用K近鄰算法實(shí)現(xiàn)小說(shuō)鑒黃
- Go語(yǔ)言實(shí)現(xiàn)漢諾塔算法
- Go語(yǔ)言通過(guò)Luhn算法驗(yàn)證信用卡卡號(hào)是否有效的方法
- go語(yǔ)言睡眠排序算法實(shí)例分析
- Go語(yǔ)言實(shí)現(xiàn)AzDG可逆加密算法實(shí)例
- Go語(yǔ)言實(shí)現(xiàn)的樹(shù)形結(jié)構(gòu)數(shù)據(jù)比較算法實(shí)例
- Go語(yǔ)言算法之尋找數(shù)組第二大元素的方法
- Golang排列組合算法問(wèn)題之全排列實(shí)現(xiàn)方法