3

我有2个班级,一个父母和一个孩子。


Class Test
    Private Test_Text

    Private Sub Class_Initialize()  
        Test_Text = "Hello"
    End Sub  

    Private Sub Class_Terminate()   

    End Sub 

    Public Property Get Text
        Text = Test_Text
    End Property

    Public Property Let Text(ByVal strIn)
        Test_Text = strIn
    End Property
End Class

Class SubTest
    Public SubTest_Test 
    Private SubTest_Interger

    Private Sub Class_Initialize()  
        Set SubTest_Test = New Test
    End Sub  

    Private Sub Class_Terminate()   
        Set SubTest_Test = Nothing
    End Sub

    Public Property Get int
        int = SubTest_Integer
    End Property

    Public Property Let int(ByVal intIn)
        SubTest_Integer = intIn
    End Property    
End Class

因为我已经公开了 SubTest_Test 我可以像这样通过子类访问它


Set MyTest = New SubTest
MsgBox MyTest.SubTest_Test.Text

这是可以接受的还是我应该将 SubTest_Test 设为私有并在子类中写入属性以访问父属性?

编辑:我想问题应该是,直接访问父级是否存在任何安全/可用性问题。
从可用性的角度来看,我越想越多,最好对使用子类的任何人隐藏父级。这样,当您从子类创建对象时,您不必了解父类的任何信息。

4

3 回答 3

2

由于这是HAS-A您的两个班级之间的关系,所以我认为您应该保持原样。你不需要为不需要的东西引入封装代码。

这是一个伪代码示例:

class Engine
    [method] start()

class Car
    [property] Engine

理想情况下,您希望将其引用Engine为如下属性Car

Car.Engine.start()

另一种方法是编写额外的代码Car以将方法包装在Engine. 虽然您可以这样做,但它没有多大意义,因为您将只是编写从Carto的传递方法Engine

于 2009-01-19T21:57:07.277 回答
1

no - this violates the Law of Demeter; rethink the interface - under what circumstances would someone need to access the Text property of the enclosed Test object in a SubTest object? If these situations make sense, you'll need to expose Text as a property in SubTest.

Given the names I would have expected SubTest to inherit from Test and thus automatically expose the Text property, but thankfully I have forgotten VBSCRIPT so I can't remember if it even supports inheritance ;-)

于 2009-01-20T04:29:49.713 回答
0

我会说这取决于您要公开的属性的数量。但是封装始终是一个很好的规则。如果 Text 是您将要访问的唯一属性,我很可能会将 SubTest_Test 设为私有并包装该属性。

于 2009-01-19T21:57:56.620 回答