creational.go 1.8 KB

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