Go语言委托 | 青训营笔记

171 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 10 天,记录一下对 Go 语言委托的学习。

什么是委托(delegation)

委托是面向对象程序设计中类之间的三种关系之一(另外两种是继承和组合),是指使用另一个对象(发送者)的上下文,对一个对象(接收者)的成员(属性或方法)求值。通过把发送者对象传递给接收者对象,任何面向对象语言都可以做显式的委托。如果语言特性支持成员查询规则,则可以做隐式的委托。如 java 语言不支持隐式委托,而 go 语言是支持的,这也给开发者带来了很大的便利。

举例:显式委托和隐式委托

定义一个名为 Rectangle 的结构体表示矩形,包含 Height 和 Width 两个成员以及一个求面积的 Size 方法。

 type Rectangle struct {
     Height int
     Width int
 }
 ​
 func (r *Rectangle) Size() int {
     return r.Height * r.Width
 }
显式委托

定义一个名为 TextRectangle 的结构体,包含 Content 和 Shape 两个成员,值得注意的是 Shape 的类型为 Rectangle。显示定义 Height、Width 方法,直接返回 Shape 的 Height、Width;显示定义 Size 方法,直接调用 Shape 的 Size 方法。这样就形成了一种显式委托。

 type TextRectangle struct {
     Content string
     Shape Rectangle
 }
 ​
 func (r *TextRectangle) Height() int {
     return r.Shape.Height
 }
 ​
 func (r *TextRectangle) Width() int {
     return r.Shape.Width
 }
 ​
 func (r *TextRectangle) Size() int {
     return r.Shape.Size()
 }

在代码上,会出现以下等价的调用。

 textRectangle := TextRectangle{Content: "text", Shape: Rectangle{1, 2}}
 ​
 // 等价
 height = textRectangle.Height()
 height = textRectangle.Shape.Height
 ​
 // 等价
 width = textRectangle.Width()
 width = textRectangle.Shape.Width
 ​
 // 等价
 size = textRectangle.Size()
 size = textRectangle.Shape.Size()
隐式委托

Go 语言支持隐式委托,其语法类似于在结构体内又嵌入了一个结构体。

定义一个名为 TextRectangle_ 的结构体,只包含 Content 一个成员,并且嵌入一个Rectangle 类型的结构体。这样就形成了一种隐式委托。与显式委托相比,隐式委托更加简洁。

 type TextRectangle_ struct {
     Content string
     Rectangle
 }

在代码上,会出现以下等价的调用。

 textRectangle_ := TextRectangle_{Content: "text", Rectangle: Rectangle{1, 2}}
 ​
 // 等价
 height = textRectangle_.Height
 height = textRectangle_.Rectangle.Height
 ​
 // 等价
 width = textRectangle_.Width
 width = textRectangle_.Rectangle.Width
 ​
 // 等价
 size = textRectangle_.Size()
 size = textRectangle_.Rectangle.Size()