当避免全局变量(/ state)时,我发现自己将对象向后链接到其父对象。我这样做了吗?如果不解释原因?以及如何?

时间:2014-09-15 08:50:49

标签: go

注意:我只是选择当前的结构/示例来解释问题。

type MsgBoxFactory struct{
    db *dbSql //contains conn-pool and other DB related settings/flags
}

func (f *MsgBoxFactory) NewMsgBox(userId string) {
    return MsgBox{userId, f.db} //f.db link is inevitable
}

type MsgBox struct {
    ownerId string
    db *dbSql
}

func (m *MsgBox) NewMessage(content string) *Message {
    return Message{content, *m.dbSql} //m.dbSql link is inevitable
}

type Message struct {
    content string
    //other fields such as recipents, isRead, created time etc.

    db *dbSql
}

func (m *Message) Send(to string) {
    message.to = to  //just imagine this saves the message to database.
    m.db.Save(message)
}

我倾向于称之为"向后引用" [我不知道实际名称] ......这是唯一的方法吗?以前我是"向后引用"整个父对象。现在我发现自己"向后引用" config / dbconn等对象......

这是一个好方法吗?什么更好?

哦,我也尝试过关闭以至少从视图中删除它。

type Message Struct{
    content string

    Send func(string) error // the problem is `json:"-"` needs to be added. Else the objects are not json compatible
}

func (m *MsgBox) NewMsg(content string) *Message {
    msg := &Message{ content }
    msg.Send = func(to string) error {
        return m.db.Save(msg)
    }
}

基本上,代码看起来几乎同样混杂着不必要的复杂性/代码

编辑:这个问题并不具体。刚发布它因为我用go。任何标签建议都可以为更广泛的社区提出问题。

1 个答案:

答案 0 :(得分:1)

我通常会实现模型助手关系。

其中MsgBox是您的模型,其中包含所有数据特定元素(无DB相关元素)。

MsgBoxHelper执行与数据库相关的所有工作。 (即

err := MsgBoxHelper.Save(MsgBox)
msgBox, err := MsgBoxHelper.Load(Key)

编辑:

这种方法的优势在于它将您的模型与数据存储区分离,如果您希望更改基础技术(这种情况不常发生),这应该会更容易。在实践中,如果您开始执行缓存等操作,它会更有用。

如果您通常在模型中引用其他结构,即

type MsgBox struct {
    Colour *MsgBoxColour
    ...
}

type MsgBoxColor struct {
    ID int
    ...
}

然后当您在MsgBoxHelper中加载Model时,使用存储在MsgBoxColour表中的ID调用MsgBoxColourHelper,然后返回MsgBoxColour,然后将其与返回的MsgBox关联。