-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactory.go
107 lines (86 loc) · 1.75 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
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package pattern
import "fmt"
// 工厂方法模式
type PType int
const (
ProductA PType = 1
ProductB PType = 2
)
type Factory struct {
}
func (f *Factory) Generate(t PType) Product {
switch t {
case ProductA:
return &Product1{}
case ProductB:
return &Product2{}
default:
return nil
}
}
type Product interface {
create()
}
type Product1 struct {
}
func (p *Product1) create() {
fmt.Println("create product1")
}
type Product2 struct {
}
func (p *Product2) create() {
fmt.Println("create product2")
}
func FactoryTest() {
factory := new(Factory)
p1 := factory.Generate(ProductA)
p1.create()
p2 := factory.Generate(ProductB)
p2.create()
}
// 抽象工厂模式
type BigFactory interface {
Generate(t PType) Product
}
type expensiveFactory struct {
}
func (e *expensiveFactory) Generate(t PType) Product {
switch t {
case ProductA:
fmt.Println("generate expensive product")
return &Product1{}
case ProductB:
fmt.Println("generate expensive product")
return &Product2{}
default:
return nil
}
}
type cheapFactory struct {
}
func (c *cheapFactory) Generate(t PType) Product {
switch t {
case ProductA:
fmt.Println("generate cheap product")
return &Product1{}
case ProductB:
fmt.Println("generate expensive product")
return &Product2{}
default:
return nil
}
}
// todo:正常来说差异应该体现在product层面,没想好怎么表示,稍后改进
func AbstractFactoryTest() {
expensiveFactory := new(expensiveFactory)
cheapFactory := new(cheapFactory)
p1 := expensiveFactory.Generate(ProductA)
p1.create()
p2 := expensiveFactory.Generate(ProductB)
p2.create()
fmt.Println("==========================")
p3 := cheapFactory.Generate(ProductA)
p3.create()
p4 := cheapFactory.Generate(ProductB)
p4.create()
}