-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathsimplefactory.go
72 lines (57 loc) · 1.03 KB
/
simplefactory.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
package main
import (
"fmt"
)
type Action interface {
Move(int) int
}
type Animal struct {
Name string
}
type Bird struct {
Animal
}
func (this *Bird) Move(num int) int {
fmt.Printf("I am a bird, I flyed %d meters.\n", num)
return num
}
type Fish struct {
Animal
}
func (this *Fish) Move(num int) int {
fmt.Printf("I am a fish, I swimmed %d meters.\n", num)
return num
}
type Dog struct {
Animal
}
func (this *Dog) Move(num int) int {
fmt.Printf("I am a dog, I flying %d meters.\n", num)
return num
}
type AnimalFactory struct {
}
func NewAnimalFactory() *AnimalFactory {
return &AnimalFactory{}
}
func (this *AnimalFactory) CreateAnimal(name string) Action {
switch name {
case "bird":
return &Bird{}
case "fish":
return &Fish{}
case "dog":
return &Dog{}
default:
panic("error animal type")
return nil
}
}
func main() {
bird := NewAnimalFactory().CreateAnimal("bird")
bird.Move(100)
fish := NewAnimalFactory().CreateAnimal("fish")
fish.Move(200)
dog := NewAnimalFactory().CreateAnimal("dog")
dog.Move(300)
}