Technique/Tips一个小技术

多态的要素

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. //多态的要素
  6. //有一个父类(有接口) ,interface接口的本质是一个指针
  7. type AnimalIF interface {
  8. Sleep()
  9. GetColor() string //获取动物的颜色
  10. GetType() string //获取动物的种类
  11. }
  12. //具体的类,子类实现了父类的所有接口方法
  13. type Cat struct {
  14. color string //猫的颜色
  15. }
  16. //子类cat完全实现一个接口
  17. func (this *Cat) Sleep() {
  18. fmt.Println("Cat is sleep")
  19. }
  20. func (this *Cat) GetColor() string {
  21. return this.color
  22. }
  23. func (this *Cat) GetType() string {
  24. return "Cat"
  25. }
  26. //具体的类
  27. type Dog struct {
  28. color string //猫的颜色
  29. }
  30. //子类dog完全实现一个接口
  31. func (this *Dog) Sleep() {
  32. fmt.Println("Cat is sleep")
  33. }
  34. func (this *Dog) GetColor() string {
  35. return this.color
  36. }
  37. func (this *Dog) GetType() string {
  38. return "Dog"
  39. }
  40. func showAnimal(animal AnimalIF) {
  41. animal.Sleep() //多态
  42. fmt.Println("color=", animal.GetColor())
  43. fmt.Println("kind=", animal.GetType())
  44. }
  45. func main() {
  46. //父类类型的变量(指针)指向(引用)子类的具体数据变量
  47. /* var animal AnimalIF //接口的数据类型,父类指针
  48. animal = &Cat("Green")
  49. animal.Sleep() //调用cat的sleep方法,多态现象
  50. animal = &Dog("Yellow")
  51. animal.Sleep() //调用dog的sleep方法,多态现象
  52. */
  53. cat := Cat{"Green"}
  54. dog := Dog{"Yellow"}
  55. showAnimal(&cat)
  56. showAnimal(&dog)
  57. }

interface{}

可以引用任意的数据类型