gpt4 book ai didi

.net - OO 模式 : Shared work between abstract base class and subclasses

转载 作者:行者123 更新时间:2023-12-04 22:37:57 26 4
gpt4 key购买 nike

我有一个抽象基类 T ,来自哪个类 AB继承。我现在有一个操作(在 T 上),它需要在 A 中稍微不同的实现和 B ,但大部分代码都是一样的。让我给你举个例子:有两种可能来实现类似 .Clone 的东西。方法:

Public MustInherit Class T
Protected MustInherit Function _DoClone() As T

Public Function Clone() As T
Dim clone = Me._DoClone() ' do the subclass-specific stuff '
... ' do the shared stuff '
End Function
End Class

Public Class A
Inherits T

Protected Overrides Function _DoClone() As T
... ' do the subclass-specific stuff '
End Function
End Class

或者
Public MustInherit Class T
Protected Sub _DoClone(clone As T)
... ' do the shared stuff '
End Function

Public MustInherit Function Clone() As T
End Class

Public Class A
Inherits T

Public Overrides Function Clone() As T
Dim clone = ... ' do the subclass-specific stuff '
Me._DoClone(clone)
End Function
End Class

(示例在 VB.NET 中,但同样的问题适用于 C#、Java 等。)

我的问题:
  • 是否有明显首选的选项?
  • 这是一个众所周知的模式,有一个名字(以便我可以做更多的研究)?
  • 对于这种情况(即 _Do...),是否有完善的命名约定?
  • 最佳答案

    看起来像 Template method图案:

    The template method is used to:

    • let subclasses implement (through method overriding) behavior that can vary
    • avoid duplication in the code: you look for the general code in the algorithm, and implement the variants in the subclasses
    • control at what point(s) subclassing is allowed.

    关于.net - OO 模式 : Shared work between abstract base class and subclasses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2340672/

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