-
Notifications
You must be signed in to change notification settings - Fork 51
/
bean_factory.go
61 lines (47 loc) · 1.07 KB
/
bean_factory.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package aop
import (
"github.com/gogap/errors"
)
type BeanFactory interface {
RegisterBean(id string, value interface{}) BeanFactory
GetBean(id string) (bean *Bean, err error)
}
type BeanFactoryAware interface {
SetBeanFactory(factory BeanFactory)
}
type ClassicBeanFactory struct {
beans map[string]*Bean
}
func NewClassicBeanFactory() BeanFactory {
return &ClassicBeanFactory{
beans: make(map[string]*Bean),
}
}
func (p *ClassicBeanFactory) GetBean(id string) (bean *Bean, err error) {
if id == "" {
err = ErrBeanIDShouldNotBeEmpty.New()
return
}
if v, exist := p.beans[id]; exist {
return v, nil
}
return nil, ErrBeanNotExist.New(errors.Params{"id": id})
}
func (p *ClassicBeanFactory) RegisterBean(id string, beanInstance interface{}) (factory BeanFactory) {
var err error
defer func() {
if err != nil {
panic(err)
}
}()
if _, exist := p.beans[id]; exist {
err = ErrBeanAlreadyRegistered.New(errors.Params{"id": id})
return
}
var bean *Bean
if bean, err = NewBean(id, beanInstance); err != nil {
return
}
p.beans[id] = bean
return p
}