基础结构
type Human interface {
SayHello()
}
type Man struct {
}
func (m *Man) SayHello() {
fmt.Println("Hello,I am a man ")
}
type Woman struct {
}
func (w *Woman) SayHello() {
fmt.Println("Hello,I am a woman")
}
simpleFactory.go
// 简单工厂
type SimpleFactory struct {
cache map[string]CreateFunc // 缓存实例的创建方式
}
type CreateFunc func() Human
var (
instance *SimpleFactory // 工厂单例
once sync.Once // 用来保证instance只会被初始化一次
)
// 获取工厂实例
func New() *SimpleFactory {
once.Do(func() {
instance = &SimpleFactory{
cache: map[string]CreateFunc{
"man": func() Human {
return &Man{}
},
"woman": func() Human {
return &Woman{}
},
},
}
})
return instance
}
// 获取实例
func (s *SimpleFactory) Get(key string) (Human, bool) {
if v, ok := s.cache[key]; ok {
return v(), true
}
return nil, false
}
main.go
package main
import (
"simpleFactory"
"fmt"
)
func main() {
if man, ok := simpleFactory.New().Get("man"); ok {
man.SayHello()
}
if woman, ok := simpleFactory.New().Get("woman"); ok {
woman.SayHello()
}
if child, ok := simpleFactory.New().Get("child"); ok {
child.SayHello()
}
}