---- 类之间最主要的关系有两种,它们是聚集(Aggregation)和继承(Generelization)。聚集表示类之间的关系是整体与部分的关系,例如一个家庭有一个父亲、一个母亲和若干个孩子。类之间的聚集关系又称包含关系,一个类由若干个其他类组合而成,当该类的实例被创建后,组成它的各类的实例将自动被创建。
---- 下图描述了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 |