-
Notifications
You must be signed in to change notification settings - Fork 60
container
hetiansu5 edited this page Jul 8, 2019
·
1 revision
对象交给容器控制,对象与对象之间松耦合。
// 注册单例对象
func (p *Container) SetSingleton(name string, singleton interface{}) {
p.Lock()
p.singletons[name] = singleton
p.Unlock()
}
// 获取单例对象
func (p *Container) GetSingleton(name string) interface{} {
return p.singletons[name]
}
// 获取实例对象
func (p *Container) GetPrototype(name string) (interface{}, error) {
factory, ok := p.factories[name]
if !ok {
return nil, ErrFactoryNotFound
}
return factory()
}
// 设置实例对象工厂
func (p *Container) SetPrototype(name string, factory factory) {
p.Lock()
p.factories[name] = factory
p.Unlock()
}