-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinjection.go
64 lines (53 loc) · 1.05 KB
/
injection.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
package headwater
type Injector[T any] interface {
Get() (bool, T)
}
type valueInjector[T any] struct {
value T
}
func (i *valueInjector[T]) Get() (bool, T) {
if i == nil {
return false, GetZero[T]()
}
return true, i.value
}
func CreateValue[T any](value T) Injector[T] {
return &valueInjector[T]{value}
}
type factory[T any] func() T
type factoryInjector[T any] struct {
factory factory[T]
}
func (i *factoryInjector[T]) Get() (bool, T) {
if i == nil {
return false, GetZero[T]()
}
return true, i.factory()
}
func CreateFactory[T any](factory factory[T]) Injector[T] {
return &factoryInjector[T]{factory}
}
type singletonInjector[T any] struct {
factory factory[T]
value T
ok bool
done bool
}
func (i *singletonInjector[T]) Get() (bool, T) {
if i == nil {
return false, GetZero[T]()
}
if !i.done {
i.done = true
i.ok = true
i.value = i.factory()
}
return i.ok, i.value
}
func CreateSingleton[T any](factory factory[T]) Injector[T] {
return &singletonInjector[T]{
factory: factory,
ok: false,
done: false,
}
}