目录

  1. 单例模式
  2. 简单工厂模式
  3. 工厂方法模式
  4. 抽象工厂模式
  5. 策略模式
  6. 观察者模式
  7. 装饰者模式
  8. 命令模式

单例模式

  • 单例模式确保程序中一个类最多只有一个实例
  • 单例模式也提供访问这个实例的全局点
  • 有一些对象其实我们只需要一个,比方说:线程池,缓存,对话框,处理偏好设置和注册表对象,日志对象等。事实上,这类对象只能有一个实例,如果制造出多个实例,就会导致许多问题产生,例如:程序的行为异常、资源使用过量,或者是不一致的结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import "sync"

//Singleton 是单例模式类
type Singleton struct{}

var singleton *Singleton
var once sync.Once

//GetInstance 用于获取单例模式对象
func GetInstance() *Singleton {
once.Do(func() {
singleton = &Singleton{}
})

return singleton

简单工厂模式

  • go 语言没有构造函数一说,所以一般会定义NewXXX函数来初始化相关类。 NewXXX 函数返回接口时就是简单工厂模式,也就是说Golang的一般推荐做法就是简单工厂。
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
import "fmt"

//API is interface
type API interface {
Say(name string) string
}

//NewAPI return Api instance by type
func NewAPI(t int) API {
if t == 1 {
return &hiAPI{}
} else if t == 2 {
return &helloAPI{}
}
return nil
}

//hiAPI is one of API implement
type hiAPI struct{}

//Say hi to name
func (*hiAPI) Say(name string) string {
return fmt.Sprintf("Hi, %s", name)
}

//HelloAPI is another API implement
type helloAPI struct{}

//Say hello to name
func (*helloAPI) Say(name string) string {
return fmt.Sprintf("Hello, %s", name)
}

工厂方法模式

  • 定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。
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
//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
}

抽象工厂模式

  • 提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类
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
import "fmt"

//OrderMainDAO 为订单主记录
type OrderMainDAO interface {
SaveOrderMain()
}

//OrderDetailDAO 为订单详情纪录
type OrderDetailDAO interface {
SaveOrderDetail()
}

//DAOFactory DAO 抽象模式工厂接口
type DAOFactory interface {
CreateOrderMainDAO() OrderMainDAO
CreateOrderDetailDAO() OrderDetailDAO
}

//RDBMainDAP 为关系型数据库的OrderMainDAO实现
type RDBMainDAO struct{}

//SaveOrderMain ...
func (*RDBMainDAO) SaveOrderMain() {
fmt.Print("rdb main save\n")
}

//RDBDetailDAO 为关系型数据库的OrderDetailDAO实现
type RDBDetailDAO struct{}

// SaveOrderDetail ...
func (*RDBDetailDAO) SaveOrderDetail() {
fmt.Print("rdb detail save\n")
}

//RDBDAOFactory 是RDB 抽象工厂实现
type RDBDAOFactory struct{}

func (*RDBDAOFactory) CreateOrderMainDAO() OrderMainDAO {
return &RDBMainDAO{}
}

func (*RDBDAOFactory) CreateOrderDetailDAO() OrderDetailDAO {
return &RDBDetailDAO{}
}

//XMLMainDAO XML存储
type XMLMainDAO struct{}

//SaveOrderMain ...
func (*XMLMainDAO) SaveOrderMain() {
fmt.Print("xml main save\n")
}

//XMLDetailDAO XML存储
type XMLDetailDAO struct{}

// SaveOrderDetail ...
func (*XMLDetailDAO) SaveOrderDetail() {
fmt.Print("xml detail save")
}

//XMLDAOFactory 是RDB 抽象工厂实现
type XMLDAOFactory struct{}

func (*XMLDAOFactory) CreateOrderMainDAO() OrderMainDAO {
return &XMLMainDAO{}
}

func (*XMLDAOFactory) CreateOrderDetailDAO() OrderDetailDAO {
return &XMLDetailDAO{}
}

策略模式

  • 针对接口编程,而不是针对实现编程
  • 定义了算法族,分别封装起来,让他们之间可以互相替换,此模式让算法变化独立于使用算法的客户
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
import "fmt"

type PaymentContext struct {
Name, CardID string
Money int
payment PaymentStrategy
}

func NewPaymentContext(name, cardid string, money int, payment PaymentStrategy) *PaymentContext {
return &PaymentContext{
Name: name,
CardID: cardid,
Money: money,
payment: payment,
}
}

func (p *PaymentContext) Pay() {
p.payment.Pay(p)
}

type PaymentStrategy interface {
Pay(*PaymentContext)
}

type Cash struct{}

func (*Cash) Pay(ctx *PaymentContext) {
fmt.Printf("Pay $%d to %s by cash", ctx.Money, ctx.Name)
}

type Bank struct{}

func (*Bank) Pay(ctx *PaymentContext) {
fmt.Printf("Pay $%d to %s by bank account %s", ctx.Money, ctx.Name, ctx.CardID)

}

观察者模式

  • 定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。
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
import "fmt"

type Subject struct {
observers []Observer
context string
}

func NewSubject() *Subject {
return &Subject{
observers: make([]Observer, 0),
}
}

func (s *Subject) Attach(o Observer) {
s.observers = append(s.observers, o)
}

func (s *Subject) notify() {
for _, o := range s.observers {
o.Update(s)
}
}

func (s *Subject) UpdateContext(context string) {
s.context = context
s.notify()
}

type Observer interface {
Update(*Subject)
}

type Reader struct {
name string
}

func NewReader(name string) *Reader {
return &Reader{
name: name,
}
}

func (r *Reader) Update(s *Subject) {
fmt.Printf("%s receive %s\n", r.name, s.context)
}

装饰者模式

  • 动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更具弹性的替代方案。
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
type Component interface {
Calc() int
}

type ConcreteComponent struct{}

func (*ConcreteComponent) Calc() int {
return 0
}

type MulDecorator struct {
Component
num int
}

func WarpMulDecorator(c Component, num int) Component {
return &MulDecorator{
Component: c,
num: num,
}
}

func (d *MulDecorator) Calc() int {
return d.Component.Calc() * d.num
}

type AddDecorator struct {
Component
num int
}

func WarpAddDecorator(c Component, num int) Component {
return &AddDecorator{
Component: c,
num: num,
}
}

func (d *AddDecorator) Calc() int {
return d.Component.Calc() + d.num
}

命令模式

  • 将请求封装成对象,这可以让你使用不用的请求、队列,或者日志请求来参数化其他对象。
  • 命令模式将发出请求的对象和执行请求的对象解耦。
    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
    import "fmt"

    type Command interface {
    Execute()
    }

    type StartCommand struct {
    mb *MotherBoard
    }

    func NewStartCommand(mb *MotherBoard) *StartCommand {
    return &StartCommand{
    mb: mb,
    }
    }

    func (c *StartCommand) Execute() {
    c.mb.Start()
    }

    type RebootCommand struct {
    mb *MotherBoard
    }

    func NewRebootCommand(mb *MotherBoard) *RebootCommand {
    return &RebootCommand{
    mb: mb,
    }
    }

    func (c *RebootCommand) Execute() {
    c.mb.Reboot()
    }

    type MotherBoard struct{}

    func (*MotherBoard) Start() {
    fmt.Print("system starting\n")
    }

    func (*MotherBoard) Reboot() {
    fmt.Print("system rebooting\n")
    }

    type Box struct {
    buttion1 Command
    buttion2 Command
    }

    func NewBox(buttion1, buttion2 Command) *Box {
    return &Box{
    buttion1: buttion1,
    buttion2: buttion2,
    }
    }

    func (b *Box) PressButtion1() {
    b.buttion1.Execute()
    }

    func (b *Box) PressButtion2() {
    b.buttion2.Execute()
    }