前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Golang的垂直组合思维——type embedding

Golang的垂直组合思维——type embedding

作者头像
李海彬
发布2019-05-08 11:37:22
1.1K0
发布2019-05-08 11:37:22
举报
文章被收录于专栏:Golang语言社区

作者:Ovenvan 来源:简书

什么是Golang的正交组合-垂直组合思维:Tony Bai的博客 - Coding in GO way - Orthogonal Composition

Go语言通过type embedding实现垂直组合。组合方式莫过于以下这么几种: a):construct interface by embedding interface b):construct struct by embedding interface c):construct struct by embedding struct Go语言中没有继承,但是可以用结构体嵌入实现继承,还有接口这个东西。现在问题来了:什么场景下应该用继承,什么场景下应该用接口。这里从一个实际的案例出发。

问题描述:

网游服务器中的一个例子。假设每个实体都有一个ObjectID,每一个实例都有一个独一无二的ObjectID。用面向对象的观点,就是有一个Object对象,里面有getID()方法,所有对象都是继承自Object对象。 Creature继承Object,表示游戏中的生物。然后像Monster,Human,都继承自Creature的。Item也继承自Object,表示物品类。除了像装备这种很直观的物品,尸体这类Corpse也是继承自Item的。而尸体又有分MonsterCorpse和HumanCorpse等。 Effect也继承自Object,表示效果类。比如玩家身上的状态。还有其它很多很多,全是以Object为基类的。 总之,Object是一个最下面的基类,直接的派生类很多,派生类的派生类更多,这样一颗继承树结构。

实现方法:

construct struct by embedding struct

这是最简单的继承的方式:

代码语言:javascript
复制
 1//construct struct by embedding struct
 2type Object struct{
 3    ID uint
 4}
 5type Creature sturct {
 6    Object // Creature继承自Object
 7}
 8type Monster struct {
 9    Creature // Monster继承自Monster
10}

这样做的好处就是,Monster直接可以调用到Creature里的方法,Creature直接可以调用Object里的方法。不用重写代码。 但是,Go中没有基类指针指向派生类对象,不可以Object指向一个Monster对象,调用Monster中的方法。 而我们实际上在很多地方需要这种抽象类型机制,比如存储需要存Creature类型,使用的时候再具体用Monster类型方法。 struct中嵌入struct,被嵌入的struct的method会被提升到外面的类型中。比如stl中的poolLocal struct,对于外部来说它拥有了Lock和Unlock方法,但是实际调用时,method调用实际被传给poolLocal中的Mutex实例。

代码语言:javascript
复制
1// sync/pool.go
2  type poolLocal struct {
3      private interface{}   // Can be used only by the respective P.
4      shared  []interface{} // Can be used by any P.
5      Mutex                 // Protects shared.
6      pad     [128]byte     // Prevents false sharing.
7  }

construct interface by embedding interface

我们新建一个工程并定义Object接口:

代码语言:javascript
复制
1//object/object.go
2package object
3type Object interface {
4    GetID() uint  
5    //每一个Object的实现类型都有一个ID值,通过GetID()获取其ID
6}

Creature也定义为一个接口,他继承于Object,且拥有自己的方法Create()。为了体现继承的关系,我把它放在了子目录下:

代码语言:javascript
复制
 1//object/creature/creature.go
 2package creature
 3import (
 4    "fmt"
 5    "github.com/ovenvan/multi-inheritance/object"
 6)
 7
 8type Creature interface {
 9    object.Object
10    Create()
11}

同样Human和Monster都继承于Creature,且拥有各自独一无二的方法Human.Born()[略]和Monster.Hatch():

代码语言:javascript
复制
 1//object/creature/monster/monster.go
 2package monster
 3import (
 4    "fmt"
 5    "github.com/ovenvan/multi-inheritance/object"
 6    "github.com/ovenvan/multi-inheritance/object/creature"
 7)
 8type Monster interface {
 9    creature.Creature
10    Hatch()
11}
12type Mstr struct{/*some properties*/}

为了使Mstr能够实现接口Monster,我们需要为他实现func:

代码语言:javascript
复制
1func (this *Mstr) GetID() uint{/*your code*/}  
2func (this *Mstr) Create() {/*your code*/}
3func (this *Mstr) Hatch(){/*your code*/}
4func NewMonster () Monster{return &Monster_s{}}

这样就不会出现construct struct by embedding struct时出现的基类指针无法指向子类的问题。现在一个东西实现Object,如果它是Monster,那么一定是Creature。但属于父类的GetID和Create方法是没法复用的,也就是说对于Hum struct,我们仍需要重写GetID和Create方法。如果这些方法实现基本相同,那么将会出现大量冗余代码。

construct struct by embedding interface

为了复用父类的方法,我们必须把方法定义在父类中。于是我们就想到了在父类中创建struct供子类继承,在父类的struct中实现方法func:

代码语言:javascript
复制
 1//object/object.go
 2package object
 3type Object interface {
 4    GetID() uint
 5}
 6type Obj struct {   //needs to be public
 7    id uint
 8}
 9func (this *Obj) GetID() uint{
10    return this.id
11}

为Creature接口创建的struct Crea 通过construct struct by embedding struct继承Obj,如此便继承了GetID的方法:

代码语言:javascript
复制
 1//object/creature/creature.go
 2package creature
 3import (
 4    "fmt"
 5    "github.com/ovenvan/multi-inheritance/object"
 6)
 7type Creature interface {
 8    object.Object
 9    Create()
10}
11type Crea struct {
12    object.Obj      //struct 中绑定interface和struct的区别?
13                    // Object只实现了一个Obj实例,这个实例的作用是被继承,提供父类的代码,因此应该继承Obj,而非Object
14}
15func (t *Crea) Create(){
16    fmt.Println("This is a Base Create Method")
17}
18func (t *Crea)GetID() uint{  //override
19    fmt.Println("Override GetID from Creature")
20    return t.Obj.GetID()
21    //t.GetID()  it is a recursive call
22}

为什么是construct struct by embedding struct而不是construct struct by embedding interface?如果可以实现绑定接口而非实例的话,我们是否可以不对外公开struct Obj呢。作者至现在思考的结果是,绑定接口是可行的,但不对外公开struct Obj(换言之,让使用者无法自如的创建struct Obj)是不可行的。 之所以在此绑定了Obj struct而非Object interface,是因为我们只创建了一个Object interface的实例,省去了赋值(给interface赋struct)的麻烦。具体而言,标准库中的package context中timerCtx绑定的是cancelCtx这一个struct。

代码语言:javascript
复制
 1//context.go
 2package context
 3
 4type Context interface {
 5    //......
 6}
 7
 8type cancelCtx struct {
 9    Context
10    mu       sync.Mutex            // protects following fields
11    done     chan struct{}         // created lazily, closed by first cancel call
12    children map[canceler]struct{} // set to nil by the first cancel call
13    err      error                 // set to non-nil by the first cancel call
14}
15
16type timerCtx struct {
17    cancelCtx          //construct struct by embedding struct
18    timer *time.Timer   // Under cancelCtx.mu.
19    deadline time.Time
20}
21
22func (c *timerCtx) cancel(removeFromParent bool, err error) {
23    c.cancelCtx.cancel(false, err)  //具体调用
24    //......

需要注意的是,具体调用是、timerCtx调用cancelCtx.cancel的方法,而非(timerCtx.cancelCtx)调用cancel方法。

而如果我们希望在父类实现多个GetID的方法,并在子类中加以选择,那么我们就需要创建两个struct并分别实现不同的方法,使用construct struct by embedding interface来决定绑定哪一个struct。另外,如果使用construct struct by embedding interface,则不可以越过父类的方法(如果存在的话)去执行爷类(???)定义的方法。 为什么说不公开struct(即struct obj)不可行,因为不是在同一个package中进行赋值。也就是说必须公开对外可见后,外部才得以使用他来赋值。而使用NewObj(…)作包裹从本质而言也是一个道理。 最后我们给出Monster的代码,可以发现,他只需要实现自己独有的方法即可。当然它也可以有选择性的override父类的方法:

代码语言:javascript
复制
 1//object/creature/monster/monster.go
 2package monster
 3import (
 4    "fmt"
 5    "github.com/ovenvan/multi-inheritance/object"
 6    "github.com/ovenvan/multi-inheritance/object/creature"
 7)
 8type Monster interface {
 9    creature.Creature
10    Hatch()
11}
12type Monster_s struct {
13    creature.Crea
14    alive bool
15}
16func (t *Monster_s) Hatch(){
17    t.Create()
18    fmt.Println("After created, i was hatched")
19}
20func (t *Monster_s) Create(){
21    t.Crea.Create()
22    fmt.Println("This is an Override Create Method from monster")
23}
24func (t *Monster_s)GetID() uint{
25    fmt.Println("Override GetID from Monster")
26    //return t.Crea.GetID()
27    return t.Obj.GetID()        //直接调用父类的父类(Obj)的方法,
28                                //跳过了Creature重写的方法。
29    //t.GetID()  recursive call
30}
31
32func NewMonster (m object.ObjectManager) Monster{...}

最后看一下main.go:

代码语言:javascript
复制
 1package main
 2
 3import (
 4    "github.com/ovenvan/multi-inheritance/object/creature/monster"
 5)
 6
 7func main() {
 8    mstr:=monster.NewMonster()
 9    mstr.Hatch()
10}

我在Github-multi-inheritance上传了本次实验的Demo,包括完善了各函数的代码,大家可以通过

代码语言:javascript
复制
1go get github.com/ovenvan/multi-inheritance

下载该Demo并提出修改意见。


版权申明:内容来源网络,版权归原创者所有。除非无法确认,我们都会标明作者及出处,如有侵权烦请告知,我们会立即删除并表示歉意。谢谢。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-03-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题描述:
  • 实现方法:
  • construct struct by embedding struct
  • construct interface by embedding interface
  • construct struct by embedding interface
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档