creational.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // creational
  2. package pattern
  3. import (
  4. "fmt"
  5. "sync"
  6. )
  7. // 1. Singleton Pattern
  8. type singleton struct {
  9. data string
  10. }
  11. var (
  12. instance *singleton
  13. once sync.Once
  14. )
  15. func GetInstance() *singleton {
  16. once.Do(func() {
  17. instance = &singleton{data: "I am singleton"}
  18. })
  19. return instance
  20. }
  21. // 2. Factory Method Pattern
  22. type Animal interface {
  23. Speak() string
  24. }
  25. type Dog struct{}
  26. type Cat struct{}
  27. func (d *Dog) Speak() string { return "Woof!" }
  28. func (c *Cat) Speak() string { return "Meow!" }
  29. func CreateAnimal(animalType string) Animal {
  30. switch animalType {
  31. case "dog":
  32. return &Dog{}
  33. case "cat":
  34. return &Cat{}
  35. default:
  36. return nil
  37. }
  38. }
  39. // 3. Abstract Factory Pattern
  40. type Button interface {
  41. Paint()
  42. }
  43. type WinButton struct{}
  44. type MacButton struct{}
  45. func (w *WinButton) Paint() { fmt.Println("Windows button") }
  46. func (m *MacButton) Paint() { fmt.Println("Mac button") }
  47. type GUIFactory interface {
  48. CreateButton() Button
  49. }
  50. type WinFactory struct{}
  51. type MacFactory struct{}
  52. func (w *WinFactory) CreateButton() Button { return &WinButton{} }
  53. func (m *MacFactory) CreateButton() Button { return &MacButton{} }
  54. // 4. Builder Pattern
  55. type House struct {
  56. windows int
  57. doors int
  58. roof string
  59. }
  60. type HouseBuilder struct {
  61. house *House
  62. }
  63. func NewHouseBuilder() *HouseBuilder {
  64. return &HouseBuilder{house: &House{}}
  65. }
  66. func (b *HouseBuilder) SetWindows(count int) *HouseBuilder {
  67. b.house.windows = count
  68. return b
  69. }
  70. func (b *HouseBuilder) SetDoors(count int) *HouseBuilder {
  71. b.house.doors = count
  72. return b
  73. }
  74. func (b *HouseBuilder) SetRoof(style string) *HouseBuilder {
  75. b.house.roof = style
  76. return b
  77. }
  78. func (b *HouseBuilder) Build() *House {
  79. return b.house
  80. }
  81. // 5. Prototype Pattern
  82. type Prototype interface {
  83. Clone() Prototype
  84. }
  85. type ConcretePrototype struct {
  86. name string
  87. }
  88. func (p *ConcretePrototype) Clone() Prototype {
  89. return &ConcretePrototype{name: p.name}
  90. }