dongmuzhan4705 2018-06-22 10:32
浏览 70
已采纳

在Go中修复导入周期

So I have this import cycle which I'm trying to solve. I have this following pattern:

view/
- view.go
action/
- action.go
- register.go

And the general idea is that actions are performed on a view, and are executed by the view:

// view.go
type View struct {
    Name string
}

// action.go
func ChangeName(v *view.View) {
    v.Name = "new name"
}

// register.go
const Register = map[string]func(v *view.View) {
    "ChangeName": ChangeName,
}

And then in view.go we invoke this:

func (v *View) doThings() {
    if action, exists := action.Register["ChangeName"]; exists {
        action(v)
    }
}

But this causes a cycle because View depends on the Action package, and vice versa. How can I solve this cycle? Is there a different way to approach this?

  • 写回答

2条回答 默认 最新

  • doumengbai2031 2018-06-22 14:02
    关注

    An import cycle indicates a fundamentally faulty design. Broadly speaking, you're looking at one of the following:

    • You're mixing concerns. Perhaps view shouldn't be accessing action.Register at all, or perhaps action shouldn't be responsible for changing the names of views (or both). This seems the most likely.
    • You're relying on a concretion where you should be relying on an interface and injecting a concretion. For example, rather than the view accessing action.Register directly, it could call a method on an interface type defined within view, and injected into the View object when it is constructed.
    • You need one or more additional, separate packages to hold the logic used by both the view and action packages, but which calls out to neither.

    Generally speaking, you want to architect an application so that you have three basic types of packages:

    1. Wholly self-contained packages, which reference no other first-party packages (they can of course reference the standard library or other third-party packages).
    2. Logic packages whose only internal dependencies are of type 1 above, i.e., wholly self-contained packages. These packages should not rely on each other or on those of type 3 below.
    3. "Wiring" packages, which mostly interact with the logic packages, and handle instantiation, initialization, configuration, and injection of dependencies. These can depend on any other package except for other type 3 packages. You should need very, very few packages of this type - often just one, main, but occasionally two or three for more complex applications.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C#不用正则表达式如何全字匹配
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错