Junior — Middle
Can you explain what a Registry is and how it is used?
sobes.tech AI
Answer from AI
Registry is a design pattern that represents a centralized storage for objects or services, which can be accessed from different parts of a program. In Go, it is often used for dependency management or for storing configurations and services to avoid global variables and simplify access to shared resources.
Example of a simple Registry in Go:
package main
import "fmt"
type Service interface {
Do()
}
type Registry struct {
services map[string]Service
}
func NewRegistry() *Registry {
return &Registry{services: make(map[string]Service)}
}
func (r *Registry) Register(name string, service Service) {
r.services[name] = service
}
func (r *Registry) Get(name string) Service {
return r.services[name]
}
}
// Example service
type MyService struct{}
func (s *MyService) Do() {
fmt.Println("Service is doing something")
}
func main() {
registry := NewRegistry()
registry.Register("myService", &MyService{})
service := registry.Get("myService")
if service != nil {
service.Do()
}
}
This approach helps to centralize the creation and access to objects, making dependency management easier.