类似单例模式,享元模式也是通过共享对象来提高性能。区别在于:
- 单例模式只保存一个对象的实例,例如客户端的数据库连接对象。
- 享元模式保存一类对象的实例,例如服务端的线程池、连接池等。
Golang 示例
package mainimport ("fmt"
)type Connect struct {name string
}
func NewConnect(name string) *Connect {return &Connect{name}
}
type ConnectFactory struct {pool map[string]*Connect
}
func NewConnectFactory() *ConnectFactory {return &ConnectFactory{pool:map[string]*Connect{}}
}
func (cf *ConnectFactory) GetConnect(key string) *Connect {if _, ok := cf.pool[key]; !ok {// ... connectc := NewConnect(key)fmt.Println("NewConnect success")cf.pool[key] = c}return cf.pool[key]
}func main() {cf := NewConnectFactory()c1 := cf.GetConnect("con1")fmt.Println(c1.name)c1 = cf.GetConnect("con1")fmt.Println(c1.name)c2 := cf.GetConnect("con2")fmt.Println(c2.name)
}