Go笔记··By/蜜汁炒酸奶

Go常用设计模式简记- 结构型模式

结构型模式(Structural Patterns),它的特点是关注类和对象的组合。

策略模式

常用场景:需要采用不同策略的场景。

实际项目中,经常要根据不同的场景,采取不同的措施,也就是不同的策略。 期间可能存在多次新增或修改操作,为了解耦,需要使用策略模式,定义一些独立的类来封装不同的算法,每一个类封装一个具体的算法(即策略).

实现:

  • 策略接口 IStrategy,
  • 定义 add 和 reduce 两种策略。
  • 最后定义了一个策略执行者,可以设置不同的策略,并执行。
package main

import "fmt"

// 策略模式

// 定义一个策略类
type IStrategy interface {
	Do(int,int) int
}

// 策略类型 加
type add struct {

}

func (*add) Do(a ,b int ) int {
	return a+b
}

// 策略类型 减
type reduce struct {

}
func (*reduce)  Do(a ,b int ) int {
	return a-b
}

// 具体策略执行者
type Operator struct {
	strategy IStrategy
}

// 设置策略
func (operator *Operator)setStrategy(strategy IStrategy)  {
	operator.strategy = strategy
}

// 调用策略中的方法
func (operator *Operator) calculate(a,b int) int {
	return operator.strategy.Do(a,b)
}

func main()  {
	// 通过测试可知,可随意更改策略,同时不影响Operator的实现
	operator := Operator{}
	operator.setStrategy(&add{})
	result := operator.calculate(1,2)
	fmt.Println("add:",result)
	operator.setStrategy(&reduce{})
	result = operator.calculate(3,1)
	fmt.Println("reduce:",result)

}
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

模版模式

常用场景:需要在不改变算法框架的情况下,改变算法执行效果的场景。

模版模式 (Template Pattern) 定义一个操作中算法的骨架,而将一些步骤延迟到子类中。这种方法让子类在不改变一个算法结构的情况下,就能重新定义该算法的某些特定步骤

模板模式就是将一个类中能够公共使用的方法放置在抽象类中实现,将不能公共使用的方法作为抽象方法,强制子类去实现,这样就做到了将一个类作为一个模板,让开发者去填充需要填充的地方

package main

import "fmt"

type Cooker interface {
	fire()
	cooke()
	outFire()
}
// 类似抽象类
type CookMenu struct {

}
func (CookMenu) fire() {
	fmt.Println("开火")
}
func (CookMenu)cooke() {

}
func (CookMenu)outFire()  {
	fmt.Println("关火")
}
// 封装具体过程
func doCooke(cook Cooker)  {
	cook.fire()
	cook.cooke()
	cook.outFire()
}

type tomatoes struct {
	CookMenu
}

func (*tomatoes)cooke()  {
	fmt.Println("炒西红柿")
}

type egg struct {
	CookMenu
}

func (*egg)cooke()  {
	fmt.Println("炒鸡蛋")
}


func main() {
	atomatoes := &tomatoes{}
	doCooke(atomatoes)
	fmt.Println("Other>>>>>>>>>")
	aegg := &egg{}
	doCooke(aegg)
}
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

参考资料

Go 语言项目开发实战

预览
Loading comments...
0 条评论

暂无数据

example
预览