golang解决循环引用的方法

第一种方式:抽象出来一个接口层:

golang不允许循环import package ,如果检测到 import cycle ,会在编译时报错,通常import cycle是因为设计错误或包的规划问题。

以下面的例子为例,package a依赖package b,同事package b依赖package a

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

package a

 

import (

 "fmt"

 

 "github.com/mantishK/dep/b"

)

 

type A struct {

}

 

func (a A) PrintA() {

 fmt.Println(a)

}

 

func NewA() *A {

 a := new(A)

 return a

}

 

func RequireB() {

 o := b.NewB()

 o.PrintB()

}

package b:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

package b

 

import (

 "fmt"

 

 "github.com/mantishK/dep/a"

)

 

type B struct {

}

 

func (b B) PrintB() {

 fmt.Println(b)

}

 

func NewB() *B {

 b := new(B)

 return b

}

 

func RequireA() {

 o := a.NewA()

 o.PrintA()

}

就会在编译时报错:

import cycle not allowed
package github.com/mantishK/dep/a
  imports github.com/mantishK/dep/b
  imports github.com/mantishK/dep/a

现在的问题就是:

A depends on B
B depends on A

那么如何避免?

引入package i, 引入interface

1

2

3

4

5

package i

 

type Aprinter interface {

 PrintA()

}

让package b import package i

1

2

3

4

5

6

7

8

9

10

11

12

package b

 

import (

 "fmt"

 

 "github.com/mantishK/dep/i"

)

 

 

func RequireA(o i.Aprinter) {

 o.PrintA()

}

引入package c

1

2

3

4

5

6

7

8

9

10

11

package c

 

import (

 "github.com/mantishK/dep/a"

 "github.com/mantishK/dep/b"

)

 

func PrintC() {

 o := a.NewA()

 b.RequireA(o)

}

现在依赖关系如下:

A depends on B
B depends on I
C depends on A and B

第二种方式:建立一个组合子包

  1. type CombileAB struct {

  2. A *package_a.PackageA

  3. B *package_b.PackageB

  4. }

  5.  

第三种方式:通过callback的方式回调,把函数通过参数传入

第四种方式:通过事件总线(eventBus)解耦

 

参考文章:

https://libuba.com/2020/11/02/golang%E5%8C%85%E5%BE%AA%E7%8E%AF%E5%BC%95%E7%94%A8%E7%9A%84%E5%87%A0%E7%A7%8D%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/

https://www.jb51.net/article/145536.htm

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值