gpt4 book ai didi

ruby - 在 Go 中建模 "superclass method implementation"的最佳方法是什么?

转载 作者:IT王子 更新时间:2023-10-29 01:18:49 26 4
gpt4 key购买 nike

我正在寻找将“经典 OO”示例转换为 Go 的示例,其中一组子类自己实现了一些方法,但它们通过父类(super class)共享了一些方法的实现。我很清楚如何使用 Go 的接口(interface),我什至使用过嵌入,但我不太确定使用什么习语(如果有的话)来捕捉这种预期行为。

这是一个具体的,可能是一个非常熟悉的例子。我会用 ruby 。有两种动物,狗和牛。所有的动物都有名字,它们会说话。无论动物类型如何,设置和获取相同的方式都是相同的;他们发出的声音因子类而异。现在有一个 speak 方法,它对所有动物都是一样的,但它委托(delegate)给子类的 sound 方法。这是用 Ruby 编写的:

class Animal
def initialize(name); @name = name; end
def speak; puts "#{@name} says #{sound()}"; end
end
class Dog < Animal; def sound(); "woof"; end; end
class Cow < Animal; def sound(); "mooo"; end; end

在 Go 中如何最好地捕获它?

到目前为止我已经尝试过

type Animal struct {
name string
}

type Cow struct {
Animal
}

type Dog struct {
Animal
}

而且我已经能够像这样构建“动物”:

func (d Dog) sound() string {return "woof"}
func (c Cow) sound() string {return "mooo"}

func main() {
d := Dog{Animal{"Sparky"}}
c := Cow{Animal{"Bessie"}}
fmt.Println(d.name)
fmt.Println(c.sound())
}

但我觉得我的做法全错了。我知道我可以将 sound() 放在界面中,但是特定的动物是发声器,而不是真正的动物。如果 Animal 成为界面,我就无法共享名称和说话代码。我意识到 Go 的设计者只使用接口(interface)并选择不直接支持这个经典的 OO 用例,就像我们在 Ruby、Python、Java 等中看到的那样,但我怀疑应该有一些 模拟这个的成语或最佳实践。这样做的首选方式是什么?

最佳答案

but I suspect there should be some idiom or best practice for simulating this.

不,没有。

如果确实出现类似的情况(在实际代码中并不常见,但主要出现在 Java/Ruby/任何代码的翻译中):interface Named { Name() string }interface Sounder { Sound() } 组合成 interface Animal {Named, Sounder} 并传递这些动物。

同样:“首选方式”是在没有继承的情况下重构解决方案。

关于ruby - 在 Go 中建模 "superclass method implementation"的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19087603/

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