-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactory.go
88 lines (67 loc) · 1.89 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
77
78
79
80
81
82
83
84
85
86
87
88
package sputnik
import (
"fmt"
)
// BlockFactory should be provided for every block in the process
type BlockFactory func() *Block
type BlockFactories map[string]BlockFactory
// BlockFactory registered in the process via RegisterBlockFactory
// Please pay attention that panic called for any error during registration.
//
// Use init() for registration of BlockFactory
//
// func init() {
// sputnik.RegisterBlockFactory("syslogPublisher", slpbFactory)
// }
func RegisterBlockFactory(name string, bf BlockFactory) {
if name == "" {
panic("RegisterBlockFactory: empty block name")
}
if bf == nil {
panic(fmt.Errorf("RegisterBlockFactory: nil block factory for %s", name))
}
if blockFactories == nil {
blockFactories = make(map[string]BlockFactory)
}
err := RegisterBlockFactoryInner(name, bf, blockFactories)
if err != nil {
panic(err)
}
}
func DefaultFactories() BlockFactories {
if blockFactories == nil {
blockFactories = make(map[string]BlockFactory)
}
return blockFactories
}
func RegisterBlockFactoryInner(name string, bf BlockFactory, facts BlockFactories) error {
if _, ok := facts[name]; ok {
return fmt.Errorf("RegisterBlockFactory: %s already registered", name)
}
facts[name] = bf
return nil
}
func Factory(name string) (BlockFactory, error) {
bfs := DefaultFactories()
fct, exists := bfs[name]
if !exists {
return nil, fmt.Errorf("factory for %s does not exist", name)
}
return fct, nil
}
func (bfs BlockFactories) createByName(name string) (blk *Block, exist bool) {
fct, ok := bfs[name]
if !ok {
return nil, false
}
bl := fct()
return bl, true
}
func (bfs BlockFactories) createByDescr(bd *BlockDescriptor) (blk *Block, err error) {
blk, ok := bfs.createByName(bd.Name)
if !ok {
return nil, fmt.Errorf("Creation of block [name: %s resp: %s] failed", bd.Name, bd.Responsibility)
}
return blk, nil
}
var blockFactories = make(map[string]BlockFactory)