gpt4 book ai didi

vba - 面向对象风格 - 在哪里定义属性?编程语言

转载 作者:行者123 更新时间:2023-12-02 22:55:09 24 4
gpt4 key购买 nike

我对面向对象编程很陌生,并试图让我的风格正确。

我经常有一个对象,其属性是包含其他对象的字典。将其命名为“Team”类,其中包含“Player”类。

现在假设每次将玩家添加到团队时,我都希望更新团队的平均年龄。

我最喜欢的解决方案:

Sub Main中我应该说

 Team.add(Player)

然后在Team中,方法add是:

 Public Sub Add(Player As CPlayer):
pPlayers.Add Player.Name, Player
Me.UpDateAvgAge(Player.Age)
End Sub

现在我可以想象至少一种替代方法:

中:

Team.add(Player)
Team.UpDateAvgAge(Player.Age)

并且 add 方法当然不应该有 Me.UpDateAvgAge(Player.Age) 行。

不用说,这只是最简单的例子。在现实生活中,每次我“添加”某些内容时,都会“更新”许多属性。

程序员对于如何进行此添加/更新是否达成共识?有什么指导方针吗?

提前谢谢!

最佳答案

我可以想象这样的事情。当新玩家添加到集合中时,CTeam 类会立即预先计算团队成员的年龄总和。然后只需使用这个数字,而不必循环遍历所有项目并计算数字。但是,您必须更新该值,以防成员从集合中删除等。您必须决定这项工作是否合适,或者您是否只是在需要时计算所有值(意味着没有缓存)。

您还可以向 CTeam 类添加事件,以便让订阅者知道新的团队成员已添加到集合中。就像这个例子中的那样,UserForm1 是订阅者,当 CTeam 类的发布者创建新玩家时,它会收到通知。 HTH

' CTeam 类:

Public Event PlayerWasAdded(player As CPlayer)

Private m_players As VBA.Collection
Private m_sumTeamAge As Single

Private Sub Class_Initialize()
Set m_players = New VBA.Collection
End Sub

Public Sub Add(player As CPlayer)
m_players.Add player, player.Name
m_sumTeamAge = m_sumTeamAge + player.Age
RaiseEvent PlayerWasAdded(player)
End Sub

Public Property Get AverageAge() As Single
If m_players.Count > 0 Then
AverageAge = m_sumTeamAge / m_players.Count
Else
AverageAge = 0
End If
End Property

'UserForm1 类:

Private WithEvents m_team As CTeam

Private Sub UserForm_Initialize()
Dim i As Integer

Set m_team = New CTeam

For i = 1 To 5
m_team.Add CreateNewPlayer(i)
Next
End Sub

Private Sub m_team_PlayerWasAdded(player As CPlayer)
MsgBox "New player " & player.Name & " was added. Do something ...", vbInformation
End Sub

Private Sub ShowAverageAge_Click()
MsgBox "Average age of team member is: " & m_team.AverageAge, vbInformation
End Sub

Private Sub AddNewPlayer_Click()
m_team.Add CreateNewPlayer(...)
End Sub

Private Function CreateNewPlayer(platerIndex As Integer) As CPlayer
Dim upperbound As Integer: upperbound = 35
Dim lowerbound As Integer: lowerbound = 18
Dim player As CPlayer

Set player = New CPlayer
player.Name = "Player_" & platerIndex
player.Age = Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
Set CreateNewPlayer = player
End Function

关于vba - 面向对象风格 - 在哪里定义属性?编程语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22780480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com