go 语言的 struct 可以使用组合来引入另外一个结构,以获得该结构定义的变量和函数。结合 interface,可以模拟面向对象中的继承和多态,但是行为有差异。
以下是 go composite 的示例代码:

  1. type IAnimal interface {
  2. Eat()
  3. Sleep()
  4. EatThenSleep()
  5. }
  6. type Animal struct {
  7. Name string
  8. }
  9. func (d Animal) Eat() {
  10. fmt.Println("animal " + d.Name + " is eating...")
  11. }
  12. func (d Animal) Sleep() {
  13. fmt.Println("animal " + d.Name + " is sleeping...")
  14. }
  15. func (d Animal) EatThenSleep() {
  16. d.Eat()
  17. d.Sleep()
  18. }
  19. type Dog struct {
  20. Animal // 类似继承
  21. }
  22. func (d Dog) Eat() {
  23. // 类似覆盖
  24. fmt.Println("dog " + d.Name + " is eating quickly...")
  25. }
  26. func main() {
  27. var d IAnimal = Dog{Animal{"dog"}}
  28. // 这里会调用 Animal.Eat,而不是 Dog.Eat,这个跟面向对象的动态绑定是不一样的
  29. // Dog 本身没有 EatThenSleep 方法,所以会跳到 Dog.Animal.EatThenSleep 方法
  30. // Dog.Animal.EatThenSleep 方法会调用 Dog.Animal.Eat 而非 Dog.Eat
  31. d.EatThenSleep()
  32. }

以下是 Python 编写的代码:

  1. class Animal(object):
  2. def __init__(self, name):
  3. self.name = name
  4. def eat(self):
  5. print('animal ' + self.name + ' is eating')
  6. def sleep(self):
  7. print('animal ' + self.name + ' is sleeping')
  8. def eat_then_sleep(self):
  9. self.eat()
  10. self.sleep()
  11. class Dog(Animal):
  12. def eat(self):
  13. print('dog ' + self.name + ' is eating quickly')
  14. if __name__ == '__main__':
  15. d = Dog("d")
  16. d.eat_then_sleep() # 会调用 Dog.eat()

参考

Golang中的面向对象继承