【发布时间】:2018-12-20 17:17:55
【问题描述】:
稍微扩展一下这个问题VBA inheritance pattern
我在 VBA 中重现了一个基本的继承模式, 但我想了解是否有更有效和更简洁的方法来实现这一点。
考虑这个小测试用例。
IAnimal.cls
'declaration
Public Sub eat()
End Sub
Public Sub breathe()
End Sub
Animal.cls:超类
Implements IAnimal
' method implementation
Private Sub IAnimal_eat()
Debug.Print "I'm eating something..."
End Sub
Private Sub IAnimal_breathe()
Debug.Print "I'm brething..."
End Sub
Cat.cls : Animal 的子类
Private super As IAnimal
Implements IAnimal
Private Sub Class_Initialize()
Set super = New Animal
End Sub
'#------------------------------------------------
' methods called when object is accessed as an IAnimal implementor.
' I HAVE TO re-implement all of them also here in the subclass (in java I don't need to. It's sufficient to implement them in the superclass)
Private Sub IAnimal_eat()
Me.eat
End Sub
Private Sub IAnimal_breathe()
Me.breathe
End Sub
'#--------------------------------------------------
' subclass-only methods
' To access those methods I MUST DECLARE the object as Cat (Dim tom as Cat)
Public Sub meow()
Debug.Print "meow..."
End Sub
'#------------------------------------------------
' superclass methods
' Since I need to declare the cat object as a Cat (see above)
' I'm FORCED TO explicitly re-implement all of the superclass methods,
' even those that I don't need to override
' otherwise I can't access them
'@Override
Public Sub eat()
Debug.print "I'm eating a fish!"
End Sub
'I'm forced to re-implement also this method, in order to use it directly on a *Cat* object
'@Unnecessary-Override
Public Sub breathe()
super.breathe
End Sub
Test.bas
Sub Main()
Dim snowball As IAnimal
Set snowball = New Cat
Dim tom As Cat
Set tom = New Cat
snowball.meow 'ERROR Method or data member not found <---- cannot access the Cat-only method "meow"
tom.meow '<--- prints "meow"
' creates a Dog, another subclass of Animal
Dim pluto As Dog
Set pluto = New Dog
'create a collection for all my animals
Dim myPets As Collection
Set myPets = New Collection
myPets.Add tom
myPets.Add pluto
Call feed(myPets) '<---- prints
'I 'm eating a fish
'meow...
'I 'm eating a bone
'woof...
End Sub
' a routine for showing how to manage an heterogeneous collection of animals
Sub feed(animals As Collection)
For Each a In animals
a.eat
If TypeOf a Is Cat Then
a.meow
End If
If TypeOf a Is Dog Then
a.woof
End If
Next
End Sub
通过这样做,我可以:
- 在 Cat 和 Dog 对象上调用
eat()方法并具有特定的重写行为 - 调用仅限子类的方法(如
meow()) - 将动物的异构集合传递给
feed子例程,该子例程可以“安全地”调用Animal 超类方法并触发基于Animal 子类的特定代码
这似乎可行,但很麻烦:假设您需要实现许多 Animal 子类(Dog、Bird、Armadillo、Platypus、Demogorgon...)。 上面的模式迫使你:
- 在所有子类上重新实现 IAnimal 接口的所有方法
- (再次)重新实现所有方法,将它们从子类中公开,即使在不需要覆盖的情况下也是如此。如果您还想访问仅限子类的方法,则特别需要这样做。
所以问题是:是否有更有效/更简洁的方法来实现这个示例(并限制每个子类的代码重写)?
【问题讨论】:
-
你不能实现一个接口而不实现它的成员,这是没有办法的。但是,第 2 点提出了一个标志:如果调用代码不能将子类与任何其他子类完全相同,那么您就违反了 Liskov 替换原则 - 不需要再次重新实现所有方法并从子类中公开它们。
-
简而言之,你应该实现接口的每个成员。你可以阅读更多关于这个here的信息。
-
感谢@MathieuGuindon 指出里氏替换原则。我试图相应地修复代码
标签: vba oop inheritance catia