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
package main

import (
	"errors"
	"fmt"
	"reflect"
)

type Animal interface {
	GetName() string
}

type Dog struct {
}

type Cat struct {
}

func (u *Dog) GetName() string {
	return "I am Dog"
}

func (u *Cat) GetName() string {
	return "I am Cat"
}

var handler = make(map[int]interface{})

func registerHandler(id int, b interface{}) {
	handler[id] = b
}

func createHandler(id int) (interface{}, error) {
	if v, ok := handler[id]; ok {
		u := reflect.New(reflect.TypeOf(v)).Interface()
		return u, nil
	}
	return nil, errors.New("no register handler")
}

func main() {

	registerHandler(1, Dog{})
	registerHandler(2, Cat{})

	if u, err := createHandler(1); err == nil {
		fmt.Println(u.(Animal).GetName())
	}
	if u, err := createHandler(2); err == nil {
		fmt.Println(u.(Animal).GetName())
		fmt.Println(&u)
	}
	if u, err := createHandler(2); err == nil {
		fmt.Println(u.(Animal).GetName())
		fmt.Println(&u)
	}
}