-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtype.go
92 lines (71 loc) · 1.8 KB
/
type.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
89
90
91
92
package zebra
import (
"errors"
)
var (
ErrTypeDescriptionEmpty = errors.New("type description is empty")
ErrTypeNameEmpty = errors.New("type name is empty")
ErrTypeEmpty = errors.New("type is empty")
ErrWrongType = errors.New("type mismatch")
)
type Type struct {
Name string `json:"name"`
Description string `json:"description"`
}
type TypeConstructor func() Resource
func (t Type) Validate() error {
if t.Name == "" {
return ErrTypeNameEmpty
}
if t.Description == "" {
return ErrTypeDescriptionEmpty
}
return nil
}
type ResourceFactory interface {
New(string) Resource
Add(Type, TypeConstructor) ResourceFactory
Types() []Type
Type(string) (Type, bool)
Constructor(string) (TypeConstructor, bool)
}
type typeData struct {
Type Type
Constructor TypeConstructor
}
type typeMap map[string]typeData
func (t typeMap) New(resourceType string) Resource {
aType, ok := t[resourceType]
if !ok {
return nil
}
return aType.Constructor()
}
// Add adds a type and its factory method to the resource factory and returns the resource factory.
// The returned resource factory object can be used to add more types in a chained fashion.
func (t typeMap) Add(aType Type, constructor TypeConstructor) ResourceFactory {
t[aType.Name] = typeData{aType, constructor}
return t
}
func (t typeMap) Types() []Type {
types := make([]Type, 0, len(t))
for _, aType := range t {
types = append(types, aType.Type)
}
return types
}
func (t typeMap) Type(name string) (Type, bool) {
if aType, ok := t[name]; ok {
return aType.Type, true
}
return Type{}, false
}
func (t typeMap) Constructor(name string) (TypeConstructor, bool) {
if aType, ok := t[name]; ok {
return aType.Constructor, true
}
return nil, false
}
func Factory() ResourceFactory {
return typeMap{}
}