forked from trustmaster/goflow
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfactory.go
44 lines (38 loc) · 1.61 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
package flow
// DefaultRegistryCapacity is the capacity component registry is initialized with.
const DefaultRegistryCapacity = 64
// ComponentConstructor is a function that can be registered in the ComponentRegistry
// so that it is used when creating new processes of a specific component using
// Factory function at run-time.
type ComponentConstructor func() interface{}
// ComponentRegistry is used to register components and spawn processes given just
// a string component name.
var ComponentRegistry = make(map[string]ComponentConstructor, DefaultRegistryCapacity)
// Register registers a component so that it can be instantiated at run-time using component Factory.
// It returns true on success or false if component name is already taken.
func Register(componentName string, constructor ComponentConstructor) bool {
if _, exists := ComponentRegistry[componentName]; exists {
// Component already registered
return false
}
ComponentRegistry[componentName] = constructor
return true
}
// Unregister removes a component with a given name from the component registry and returns true
// or returns false if no such component is registered.
func Unregister(componentName string) bool {
if _, exists := ComponentRegistry[componentName]; exists {
delete(ComponentRegistry, componentName)
return true
} else {
return false
}
}
// Factory creates a new instance of a component registered under a specific name.
func Factory(componentName string) interface{} {
if constructor, exists := ComponentRegistry[componentName]; exists {
return constructor()
} else {
panic("Uknown component name: " + componentName)
}
}