Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "reflect"
  6. )
  7.  
  8. // Animal base "class".
  9. type Animal struct {
  10. Name string
  11. mean bool
  12. }
  13.  
  14. // AnimalSounder interface exposes MakeNoise() method, which provides the different Animal "sounds".
  15. type AnimalSounder interface {
  16. MakeNoise()
  17. }
  18.  
  19. // Dog is a type of Animal.
  20. type Dog struct {
  21. Animal
  22. BarkStrength int
  23. }
  24.  
  25. // Cat is a type of Animal.
  26. type Cat struct {
  27. Basics Animal
  28. MeowStrength int
  29. }
  30.  
  31. // Lion is a type of Animal.
  32. type Lion struct {
  33. Basics Animal
  34. RoarStrength int
  35. }
  36.  
  37. // MakeNoise (*Dog) barks.
  38. func (animal *Dog) MakeNoise() {
  39. animalType := reflect.ValueOf(animal).Type().Elem().Name()
  40. animal.PerformNoise(animal.BarkStrength, "BARK", animalType)
  41. }
  42.  
  43. // MakeNoise (*Cat) meows.
  44. func (animal *Cat) MakeNoise() {
  45. animalType := reflect.ValueOf(animal).Type().Elem().Name()
  46. animal.Basics.PerformNoise(animal.MeowStrength, "MEOW", animalType)
  47. }
  48.  
  49. // MakeNoise (*Lion) roars.
  50. func (animal *Lion) MakeNoise() {
  51. animalType := reflect.ValueOf(animal).Type().Elem().Name()
  52. animal.Basics.PerformNoise(animal.RoarStrength, "ROAR!! ", animalType)
  53. }
  54.  
  55. // MakeSomeNoise exposes AnimalSounder's MakeNoise() method.
  56. func MakeSomeNoise(animalSounder AnimalSounder) {
  57. animalSounder.MakeNoise()
  58. }
  59.  
  60. func main() {
  61. myDog := &Dog{
  62. Animal{
  63. Name: "Rover", // Name
  64. mean: false, // mean
  65. },
  66. 2, // BarkStrength
  67. }
  68.  
  69. myCat := &Cat{
  70. Basics: Animal{
  71. Name: "Julius",
  72. mean: true,
  73. },
  74. MeowStrength: 3,
  75. }
  76.  
  77. wildLion := &Lion{
  78. Basics: Animal{
  79. Name: "Aslan",
  80. mean: true,
  81. },
  82. RoarStrength: 5,
  83. }
  84.  
  85. MakeSomeNoise(myDog)
  86. MakeSomeNoise(myCat)
  87. MakeSomeNoise(wildLion)
  88. }
  89.  
  90. // PerformNoise is a generic method shared by all implementations of Animal.
  91. func (animal *Animal) PerformNoise(strength int, sound string, animalType string) {
  92. if animal.mean == true {
  93. strength = strength * 5
  94. }
  95.  
  96. fmt.Printf("%s (%s): \n", animal.Name, animalType)
  97.  
  98. for voice := 0; voice < strength; voice++ {
  99. fmt.Printf("%s ", sound)
  100. }
  101.  
  102. fmt.Println("\n")
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement