Advertisement
cwchen

[Go] Builder pattern demo.

Oct 7th, 2017
737
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.98 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5. )
  6.  
  7. type IAnimal interface {
  8.     Speak()
  9. }
  10.  
  11. type AnimalType int
  12.  
  13. const (
  14.     Duck AnimalType = iota
  15.     Dog
  16.     Tiger
  17. )
  18.  
  19. type DuckClass struct{}
  20.  
  21. func NewDuck() *DuckClass {
  22.     return new(DuckClass)
  23. }
  24.  
  25. func (d *DuckClass) Speak() {
  26.     fmt.Println("Pack pack")
  27. }
  28.  
  29. type DogClass struct{}
  30.  
  31. func NewDog() *DogClass {
  32.     return new(DogClass)
  33. }
  34.  
  35. func (d *DogClass) Speak() {
  36.     fmt.Println("Wow wow")
  37. }
  38.  
  39. type TigerClass struct{}
  40.  
  41. func NewTiger() *TigerClass {
  42.     return new(TigerClass)
  43. }
  44.  
  45. func (t *TigerClass) Speak() {
  46.     fmt.Println("Halum halum")
  47. }
  48.  
  49. func New(t AnimalType) IAnimal {
  50.     switch t {
  51.     case Duck:
  52.         return NewDuck()
  53.     case Dog:
  54.         return NewDog()
  55.     case Tiger:
  56.         return NewTiger()
  57.     default:
  58.         panic("Unknown animal type")
  59.     }
  60. }
  61.  
  62. func main() {
  63.     animals := make([]IAnimal, 0)
  64.  
  65.     duck := New(Duck)
  66.     dog := New(Dog)
  67.     tiger := New(Tiger)
  68.  
  69.     animals = append(animals, duck, dog, tiger)
  70.  
  71.     for _, a := range animals {
  72.         a.Speak()
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement