单例模式
package main
import "sync"
var instance *Single
var once sync.Once
type Single struct {}
func NewSingle() *Single {
once.Do(func() {
instance = new(Single)
})
return instance
}
工厂模式
package main
import (
"fmt"
)
type Phone interface {
Call()
}
type Mi struct{}
type Iphone struct{}
func (mi *Mi) Call() {
fmt.Println("喂...(mi)")
}
func (i *Iphone) Call() {
fmt.Println("喂...(iphone)")
}
type Factory struct{}
func (f *Factory) Create(name string) Phone {
switch name {
case "mi":
return new(Mi)
case "iphone":
return new(Iphone)
default:
panic("找不到这个手机:" + name)
}
}
func main() {
f := new(Factory)
p := f.Create("mi")
p.Call()
p = f.Create("iphone")
p.Call()
}
来源:oschina
链接:https://my.oschina.net/imhuayi/blog/3160338