-
Notifications
You must be signed in to change notification settings - Fork 35
/
factory.go
79 lines (67 loc) · 1.37 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
// Copyright 2017 The go-hep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rootio
import (
"fmt"
"log"
"reflect"
"sync"
)
// FactoryFct creates new values of a given type.
type FactoryFct func() reflect.Value
type factory struct {
mu sync.RWMutex
db map[string]FactoryFct // a registry of all factory functions by type name
}
func (f *factory) Len() int {
f.mu.RLock()
n := len(f.db)
f.mu.RUnlock()
return n
}
func (f *factory) Keys() []string {
f.mu.RLock()
keys := make([]string, 0, len(f.db))
for k := range f.db {
keys = append(keys, k)
}
f.mu.RUnlock()
return keys
}
func (f *factory) HasKey(n string) bool {
f.mu.RLock()
_, ok := f.db[n]
f.mu.RUnlock()
return ok
}
func (f *factory) Get(n string) FactoryFct {
f.mu.RLock()
fct, ok := f.db[n]
f.mu.RUnlock()
if ok {
return fct
}
fct = func() reflect.Value {
o := &dobject{class: n}
return reflect.ValueOf(o)
}
Factory.add(n, fct)
log.Printf("rootio: adding dummy factory for %q\n", n)
return fct
}
func (f *factory) get(n string) FactoryFct {
fct := f.Get(n)
if fct == nil {
panic(fmt.Errorf("rootio: no factory for type %q", n))
}
return fct
}
func (f *factory) add(n string, fct FactoryFct) {
f.mu.Lock()
f.db[n] = fct
f.mu.Unlock()
}
var Factory = factory{
db: make(map[string]FactoryFct),
}