概述

工厂模式是对象的生产器,解耦用户对具体的依赖。通过封闭、继承、多态把程序的耦合度降低,使程序更加灵活,容易修改,并易于复用。简单工厂模式中,各种运算方法类实现了运算接口,在业务上如果想添加一种算法方法,只需要增加一个实现接口的类,并且在工厂的类型中添加一个判断。这种设计适合用于业务逻辑并不多的情况,如果业务逻辑非常多,那么工作累就是一个很长的swuth…case结构这时候使用工厂模式会比较合适。

主要类

  • base - interface
  • concreteA - concrete class A
  • concreteB - concrete class B
  • factory - in: choice; out: base

优势

工厂类中包含了必要的逻辑判断,根据客户端的选择条件实例化相应的类,对于客户端来说,去除了与具产品的依赖

代码实现

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
/*
设计一个计算器
*/
//Operation 操作接口
type Operation interface {
SetNumber(float64, float64)
GetResult() float64
}
//BaseOperation 基础类
type BaseOperation struct {
Operation
NumberA float64
NumberB float64
}
func (bo *BaseOperation) SetNumber(numberA, numberB float64) {
bo.NumberA = numberA
bo.NumberB = numberB
}
//OperationAdd 加法运算
type OperationAdd struct {
BaseOperation
}
func (oa OperationAdd) GetResult() float64 {
return oa.NumberA + oa.NumberB
}
//OperationSub 减法运算类
type OperationSub struct {
BaseOperation
}
func (os OperationSub) GetResult() float64 {
return os.NumberA - os.NumberB
}
//OperationFactory 工厂类
type OperationFactory struct{}
func (of OperationFactory) CreateOperation(oper string) Operation {
switch oper {
default:
return nil
case "+":
return new(OperationAdd)
case "-":
return new(OperationSub)
}
}
//OperationUsage 工厂操作
func OperationUsage() {
factory := new(OperationFactory)
operation := factory.CreateOperation("+")
operation.SetNumber(1, 2)
fmt.Printf("this is add operation, 1+2=%v\n", operation.GetResult())
operation = factory.CreateOperation("-")
operation.SetNumber(2, 1)
fmt.Printf("this is sub operation, 2-1=%v\n", operation.GetResult())
}
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
/*
设计一个工厂来生产各种厂商的手机
其中初始的厂商有小米,苹果,华为
*/
//Phone interface
type Phone interface {
ShowBrand()
}
//IPhone apple
type IPhone struct {
}
func (phone IPhone) ShowBrand() {
fmt.Println("[Phone Brand]: Apple")
}
//HPhone huawei
type HPhone struct {
}
func (phone HPhone) ShowBrand() {
fmt.Println("[Phone Brand]: Huawei")
}
//XPhone xiaomi
type XPhone struct {
}
func (phone XPhone) ShowBrand() {
fmt.Println("[Phone Brand]: Xiaomi")
}
type PhoneFactory struct{}
func (factory PhoneFactory) CreatePhone(brand string) Phone {
switch brand {
default:
return nil
case "HW":
return new(HPhone)
case "XM":
return new(XPhone)
case "PG":
return new(IPhone)
}
}
func PhoneUsage() {
factory := PhoneFactory{}
phone := factory.CreatePhone("HW")
phone.ShowBrand()
}
1
2
3
4
5
6
7
8
func main() {
OperationUsage()
PhoneUsage()
}
result :
this is add operation, 1+2=3
this is sub operation, 2-1=1
[Phone Brand]: Huawei

Copyright © Ywnline 版权所有 冀ICP备20005992号-1