File tree 3 files changed +97
-0
lines changed
3 files changed +97
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 工厂方法模式
2
+
3
+ 工厂方法模式使用子类的方式延迟生成对象到子类中实现。
4
+
5
+ Go中不存在继承 所以使用匿名组合来实现
Original file line number Diff line number Diff line change
1
+ package factorymethod
2
+
3
+ //Operator 是被封装的实际类接口
4
+ type Operator interface {
5
+ SetA (int )
6
+ SetB (int )
7
+ Result () int
8
+ }
9
+
10
+ //OperatorFactory 是工厂接口
11
+ type OperatorFactory interface {
12
+ Create () Operator
13
+ }
14
+
15
+ //OperatorBase 是Operator 接口实现的基类,封装公用方法
16
+ type OperatorBase struct {
17
+ a , b int
18
+ }
19
+
20
+ //SetA 设置 A
21
+ func (o * OperatorBase ) SetA (a int ) {
22
+ o .a = a
23
+ }
24
+
25
+ //SetB 设置 B
26
+ func (o * OperatorBase ) SetB (b int ) {
27
+ o .b = b
28
+ }
29
+
30
+ //PlusOperatorFactory 是 PlusOperator 的工厂类
31
+ type PlusOperatorFactory struct {}
32
+
33
+ func (PlusOperatorFactory ) Create () Operator {
34
+ return & PlusOperator {
35
+ OperatorBase : & OperatorBase {},
36
+ }
37
+ }
38
+
39
+ //PlusOperator Operator 的实际加法实现
40
+ type PlusOperator struct {
41
+ * OperatorBase
42
+ }
43
+
44
+ //Result 获取结果
45
+ func (o PlusOperator ) Result () int {
46
+ return o .a + o .b
47
+ }
48
+
49
+ //MinusOperatorFactory 是 MinusOperator 的工厂类
50
+ type MinusOperatorFactory struct {}
51
+
52
+ func (MinusOperatorFactory ) Create () Operator {
53
+ return & MinusOperator {
54
+ OperatorBase : & OperatorBase {},
55
+ }
56
+ }
57
+
58
+ //MinusOperator Operator 的实际减法实现
59
+ type MinusOperator struct {
60
+ * OperatorBase
61
+ }
62
+
63
+ //Result 获取结果
64
+ func (o MinusOperator ) Result () int {
65
+ return o .a - o .b
66
+ }
Original file line number Diff line number Diff line change
1
+ package factorymethod
2
+
3
+ import "testing"
4
+
5
+ func compute (factory OperatorFactory , a , b int ) int {
6
+ op := factory .Create ()
7
+ op .SetA (a )
8
+ op .SetB (b )
9
+ return op .Result ()
10
+ }
11
+
12
+ func TestOperator (t * testing.T ) {
13
+ var (
14
+ factory OperatorFactory
15
+ )
16
+
17
+ factory = PlusOperatorFactory {}
18
+ if compute (factory , 1 , 2 ) != 3 {
19
+ t .Fatal ("error with factory method pattern" )
20
+ }
21
+
22
+ factory = MinusOperatorFactory {}
23
+ if compute (factory , 4 , 2 ) != 2 {
24
+ t .Fatal ("error with factory method pattern" )
25
+ }
26
+ }
You can’t perform that action at this time.
0 commit comments