【问题标题】:Aggregation relationships and instantiating objects from database storage (vb)聚合关系和从数据库存储实例化对象 (vb)
【发布时间】:2011-02-16 02:23:02
【问题描述】:

我有一个小型应用程序,它允许用户创建帐户,然后互相奖励“积分”。 UserAccount 是一个对象,Point 也是,它们之间存在聚合关系:每个 UserAccount 都有一个成员变量(PointHistory),它是一个 Points 的集合。

Point 对象只包含 UserAccount 对象发送/接收 Point 的属性。

当我简单地序列化类以保留我的对象模型时,这很好。但是,我现在正在实现一个数据库来持久化对象数据,并且在任何给定时间只会将一个/一些对象加载到内存中。为了加载对象,我有一个构造函数方法,它从数据库中的一行创建一个新的 UserAccount,还有一个类似的构造函数从数据库行创建一个点。这就是麻烦的开始——当第二个构造函数必须引用第一个构造函数尚未构造的东西时,一个对象的构造函数如何调用另一个对象的构造函数?为了完成构造,对象必须已经构造。

简单的解决方案是简单地用从数据库查询中提取的字符串集合替换 Point 对象集合 (PointHistory)。这足以满足我的目的。但是,我想知道是否有另一种不放弃 Point 对象/对象模型的方法,以及这种聚合/持久性问题是否常见?

【问题讨论】:

  • 您好,如果您觉得我的回答有用,请标记为已接受。
  • 对不起,我当时没有意识到这就是勾号的用途;当我按下向上箭头时它不起作用,因为我的帐户没有注册

标签: database vb.net object persistence aggregation


【解决方案1】:

如果我理解正确的话,UserAccount构造函数需要构造属于这个UserAccount的Points,而这些Points需要一种方式来引用当前正在构造的UserAccount?

如果是这种情况,您可以将 Me 传递给 Point 构造函数,这实际上将传递正在构造的 UserAccount。即使构造尚未完成,它也会传递 UserAccount 对象。

Class UserAccount

   Private _pointHistory As New System.Collections.Generic.List(Of MyProject.Point)

    Public Sub New()
       ...
       ...

       ' Instantiate a new point, and pass this UserAccount object into it 
       ' so that it can grab a reference
       Dim newPoint as New MyProject.Point(Me) 

       'Add the Point to this UserAccount's collection
       _pointHistory.Add(newPoint)

    End Sub

End Class


Class Point

    Private _parentAccount as MyProject.UserAccount

    Public Sub New(parentAccount as MyProject.UserAccount)

        'Store the reference to the User Account
        _parentAccount = parentAccount

    End Sub

End Class

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2014-07-13
    • 1970-01-01
    相关资源
    最近更新 更多