本文实例讲述了Go语言使用组合的方式实现多继承的方法。分享给大家供大家参考。具体实现方法如下:
在大多数面向对象的编程语言中多继承都是不支持的。因为在基于class的体系中,多继承极大地增加了编译器的复杂性。
Go语言使用组合的方式实现继承,因此也可以很简单的实现多继承。
复制代码 代码如下:
//使用组合的方式实现多继承
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
*/
}
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
*/
}
希望本文所述对大家的Go语言程序设计有所帮助。