VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > go语言 >
  • 必须掌握的Golang23种设计模式之工厂方法模式

设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。

使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。 毫无疑问,设计模式于己于他人于系统都是多赢的,设计模式使代码编制真正工程化,设计模式是软件工程的基石,如同大厦的一块块砖石一样。

项目中合理的运用设计模式可以完美的解决很多问题,每种模式在现在中都有相应的原理来与之对应,每一个模式描述了一个在我们周围不断重复发生的问题,以及该问题的核心解决方案,这也是它能被广泛应用的原因。

设计模式的分类

创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。

结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。

行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代器模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。


 

工厂方法模式使用子类的方式延迟生成对象到子类中实现。

Go中不存在继承 所以使用匿名组合来实现

查看全部设计模式:http://www.golang.ren/article/6477

factorymethod.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
package factorymethod
 
//Operator 是被封装的实际类接口
type Operator interface {
    SetA(int)
    SetB(int)
    Result() int
}
 
//OperatorFactory 是工厂接口
type OperatorFactory interface {
    Create() Operator
}
 
//OperatorBase 是Operator 接口实现的基类,封装公用方法
type OperatorBase struct {
    a, b int
}
 
//SetA 设置 A
func (o *OperatorBase) SetA(a int) {
    o.a = a
}
 
//SetB 设置 B
func (o *OperatorBase) SetB(b int) {
    o.b = b
}
 
//PlusOperatorFactory 是 PlusOperator 的工厂类
type PlusOperatorFactory struct{}
 
func (PlusOperatorFactory) Create() Operator {
    return &PlusOperator{
        OperatorBase: &OperatorBase{},
    }
}
 
//PlusOperator Operator 的实际加法实现
type PlusOperator struct {
    *OperatorBase
}
 
//Result 获取结果
func (o PlusOperator) Result() int {
    return o.a + o.b
}
 
//MinusOperatorFactory 是 MinusOperator 的工厂类
type MinusOperatorFactory struct{}
 
func (MinusOperatorFactory) Create() Operator {
    return &MinusOperator{
        OperatorBase: &OperatorBase{},
    }
}
 
//MinusOperator Operator 的实际减法实现
type MinusOperator struct {
    *OperatorBase
}
 
//Result 获取结果
func (o MinusOperator) Result() int {
    return o.a - o.b
}

 

factorymethod_test.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
package factorymethod
 
import "testing"
 
func compute(factory OperatorFactory, a, b int) int {
    op := factory.Create()
    op.SetA(a)
    op.SetB(b)
    return op.Result()
}
 
func TestOperator(t *testing.T) {
    var (
        factory OperatorFactory
    )
 
    factory = PlusOperatorFactory{}
    if compute(factory, 1, 2) != 3 {
        t.Fatal("error with factory method pattern")
    }
 
    factory = MinusOperatorFactory{}
    if compute(factory, 4, 2) != 2 {
        t.Fatal("error with factory method pattern")
    }
}

 出处:https://www.cnblogs.com/7php/p/14981102.html


相关教程