func(c *MapContainer) Get(name string) any { return c.storge[name] }
func(c *MapContainer) Init() error { // Create a slice of object names and weights for sorting type weightedObject struct { name string object Object }
var weightedObjects []weightedObject
for name, obj := range c.storge { weightedObjects = append(weightedObjects, weightedObject{name: name, object: obj}) }
// Initialize objects in the order of their weights for _, wObj := range weightedObjects { if err := wObj.object.Init(); err != nil { return fmt.Errorf("%s init error, %s", wObj.name, err) } fmt.Printf("[%s] %s init success with weight %d\n", c.name, wObj.name, wObj.object.Weight()) }
returnnil }
那我们该怎么使用呢?
当然也很简单:
准备托管对象的Container-Controller:
1 2 3 4 5 6
package ioc
var Controller Container = &MapContainer{ name: "controller", storge: make(map[string]Object), }
// example/core/app.go type app struct { hostName string port string }
funcNewApp(opts ...func(*app)error) *app { var server = new(app) for _, opt := range opts { if err := opt(server); err != nil { logger.Fatalf("Failed to apply option: %v", err) } } return server }