基础结构

    1. type Human interface {
    2. SayHello()
    3. }
    4. type Man struct {
    5. }
    6. func (m *Man) SayHello() {
    7. fmt.Println("Hello,I am a man ")
    8. }
    9. type Woman struct {
    10. }
    11. func (w *Woman) SayHello() {
    12. fmt.Println("Hello,I am a woman")
    13. }

    simpleFactory.go

    1. // 简单工厂
    2. type SimpleFactory struct {
    3. cache map[string]CreateFunc // 缓存实例的创建方式
    4. }
    5. type CreateFunc func() Human
    6. var (
    7. instance *SimpleFactory // 工厂单例
    8. once sync.Once // 用来保证instance只会被初始化一次
    9. )
    10. // 获取工厂实例
    11. func New() *SimpleFactory {
    12. once.Do(func() {
    13. instance = &SimpleFactory{
    14. cache: map[string]CreateFunc{
    15. "man": func() Human {
    16. return &Man{}
    17. },
    18. "woman": func() Human {
    19. return &Woman{}
    20. },
    21. },
    22. }
    23. })
    24. return instance
    25. }
    26. // 获取实例
    27. func (s *SimpleFactory) Get(key string) (Human, bool) {
    28. if v, ok := s.cache[key]; ok {
    29. return v(), true
    30. }
    31. return nil, false
    32. }

    main.go

    1. package main
    2. import (
    3. "simpleFactory"
    4. "fmt"
    5. )
    6. func main() {
    7. if man, ok := simpleFactory.New().Get("man"); ok {
    8. man.SayHello()
    9. }
    10. if woman, ok := simpleFactory.New().Get("woman"); ok {
    11. woman.SayHello()
    12. }
    13. if child, ok := simpleFactory.New().Get("child"); ok {
    14. child.SayHello()
    15. }
    16. }

    image.png