---- 下图描述了Family类与组成它的各类之间的关系。Family类与Father类、Mother类的关系是一对一的关系,而Family类与Child类的关系是一对多的关系。为了简化类之间的关系,我们增加了一个Children类,Children类是Child类的集合,因此Family类与Children类直接关联,形成一对一的关系。
Family------------ > Father
|
-------- > Mother
|
-------- > Childred ------ >child
---- VB6.0对类聚集关系的实现提供了较好的支持。在下面的程序中,我们仅给出了与Falimy类、Children类、Child类的具体实现有关的代码,以此为例说明类聚集关系的实现方法。
---- 程序中定义了三个类模块:Falimy类模块,Children类模块,Child类模块。在Falimy类模块中,利用属性过程,Mother类、Father类、Children类被定义为Family类的只读属性。下面是Family 类模块中声明部分的代码。
Option Explicit
Private mFather As New Father
Private mMother As New Mother
Private mChildren As New Children
Public Property Get Father() As Father
Set Father=mMother
End Property
Public Property Get Mother()As Mother
Set Mother()=mMother
End Property
Public Property Get Children() As Children
Set Children= mChildren
End Property
---- 下面是Children类模块的代码,首先在类模块的说明部分创建了集合类Collection的实例mcolChildren。在定义公共方法Add时,通过引用mcolChildren的Add方法将新的Child 对象添加到集合中,Children类被定义成Child类的集合。通过直接引用mcolChildren的属性Count定义了Children类的公共属性Count,通过直接引用mcolChildren的方法Item定义了Children类的公共方法Item。
---- 我们还可以根据需要实现其他的属性和方法。通过创建Children类,与Children类有关的所有代码都封装起来,使得Children类可以进一步重用,从而较好地体现了面向对象程序设计的原则。
Option Explicit
Private mcolChildren As New Collection
Public Property Get Count() As Long
Count = mcolChildren.Count
End Property
Public Function Add(ByVal Name As String,
ByVal BirthDayAs Date,ByVal Sex As Boolean ) As Child
Dim empNew As New Child
Static intNum As Integer
With empNew
intNum = intNum + 1
.Name = Name
.BirthDay= BirthDay
.Sex=Sex
mcolChildren.Add empNew
End With
Set Add = empNew
End Function
Public Function Item(ByVal Index As Variant) As Child
Set Item = mcolChildren.Item(Index)
End Function
---- 下面是Child类声明部分的代码。
Option Explicit
Public Name As String
Public BirthDay As Date
Public Sex As Boolean
---- 程序中还定义了一个窗体模块。在窗体上布置有三个文本框txtName、txtBirthDay、txtSex,一个列表框lstChildren,两个命令按纽cmdAddChild、cmdListChild。
---- 在窗体模块中首先创建了一个Family类的实例sbMain,Children类和Child类的实例也随之被创建。在事件过程中,仅通过引用sbMain的属性Children,我们就可以实现对Children类的各种操作。
Option Explicit
Public sbMain As New Family
Private Sub cmdAddChild_Click()
sbMain.Children.Add txtName.Text,
txtSalary.Text,txtSex.Text
txtBirthDay.Text = " "
txtName.Text = " "
txtSex.Text=" "
End Sub
Private Sub cmdListChild_Click()
Dim emp As New Child
Dim i As Long
lstChild.Clear
For i = 1 To sbMain.Children.Count
Set emp = sbMain.Children.Item(i)
lstChild.AddItem emp.Name & ", "
& emp.BirthDay&", "emp.Sex
Next
End Sub
【VB6.0中类聚集关系的实现】相关文章:
09中考英语命题作文 C02-06
我梦想中的房子高考英语作文02-06
初中英语听力训练材料02-06
2023年内蒙古包头中考总分多少,各科都是多少分?02-06
上网利与弊的短文,300字左右_500字02-06
小学必会的Be动词的用法语法知识02-06
高考英语词汇: one another与one after another的区别02-06
高中生英语作文:为什么人们选择网购02-06
浙教版五年级上册英语期中试卷02-06
职称英语理工类阅读理解(3)02-06
中级人力资源专业知识与实务练习题(7)02-06
