dongqiao2077 2013-09-30 06:21
浏览 40
已采纳

在Go中为“超类方法实现”建模的最佳方法是什么?

I am looking to translate a "classic OO" example into Go, one in which a set of subclasses implement some methods on their own but they share an implementation of some methods via their superclass. I'm well aware of how to use Go's interfaces and I've even used embedding, but I'm not quite sure what, if any, idioms to employ to capture this intended behavior.

Here's a concrete, and probably a very familiar example. I'll use Ruby. There are two kinds of animals, dogs and cows. All animals have a name and they can speak. The way you set and get the same is the same regardless of the animal type; the sound they make differs depending on the subclass. Now there is a speak method which is the same for all animals, but it delegates to the subclass's sound method. Here it is in 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

How is this best captured in Go?

So far I've tried

type Animal struct {
    name string
}

type Cow struct {
    Animal
}

type Dog struct {
    Animal
}

and I've been able to construct "animals" like so:

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())
}

But I feel I'm going about this all wrong. I know I can put sound() in an interface, but then the specific animals are sounders, not really animals. If Animal becomes the interface, I can't share the name and the speak code. I realize the designers of Go went with interfaces-only and chose not do directly support this classic OO use case the way we would see it done in Ruby, Python, Java, and so on, but I suspect there should be some idiom or best practice for simulating this. What is the preferred way of doing so?

  • 写回答

4条回答 默认 最新

  • douweibiao8471 2013-09-30 07:32
    关注

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

    No there isn't.

    If something like that does come up (and it doesn't very often in real code, but mostly in translations of Java/Ruby/whatever code): interface Named { Name() string } and interface Sounder { Sound() } combined to interface Animal {Named, Sounder} and pass those animals around.

    Again: The "prefered way" is to remodel the solution without inheritance.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制