-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory.go
76 lines (67 loc) · 1.56 KB
/
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package factory_gorl
import (
"fmt"
"reflect"
)
type Builder func(i interface{})
type Factory struct {
name string
buildType reflect.Type
parent *Factory
builder Builder
}
func NewFactory(name string, i interface{}, builder Builder) (*Factory, error) {
f := new(Factory)
f.name = name
var err error
f.buildType, err = toType(i)
if err != nil {
return nil, err
}
f.builder = builder
return f, nil
}
func NewFactoryWithParent(name string, i interface{}, parent *Factory, builder Builder) (*Factory, error) {
buildType, err := toType(i)
if err != nil {
return nil, err
}
if buildType != parent.buildType {
return nil, fmt.Errorf("factory_gorl: cannot create a factory for '%v' with parent '%v'", buildType, parent.buildType)
}
f := new(Factory)
f.name = name
f.buildType = buildType
f.parent = parent
f.builder = builder
return f, nil
}
func toType(i interface{}) (reflect.Type, error) {
t := reflect.TypeOf(i)
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf("factory_gorl: cannot create this type: '%v'", reflect.TypeOf(i))
}
return t, nil
}
func (factory *Factory) Name() string {
return factory.name
}
func (factory *Factory) Run(override Builder) interface{} {
result := reflect.New(factory.buildType)
factory.build(result.Interface())
if override != nil {
override(result.Interface())
}
return result.Interface()
}
func (factory *Factory) build(i interface{}) {
if factory.parent != nil {
factory.parent.build(i)
}
if factory.builder != nil {
factory.builder(i)
}
}