开闭原则#

类的改动是通过增加代码进行的,而不是修改源代码

这个非常简单

就是通过增加结构体,增加代码量来提高代码逻辑性

假设现在 很多人每个人有不同的职业:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type People struct{}

func (p *People) Teacher() {
fmt.Println("this people is a teacher")
}

func (p *People) Student() {
fmt.Println("this people is a student")
}

func (p *People) Driver() {
fmt.Println("this people is a driver")
}

func main() {
p := &People{}
p.Teacher()
p.Student()
p.Driver()
}

现在我要加一个警察的职业,往往我们会这样加:

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
package main

import "fmt"

// 开闭原则

type People struct{}

func (p *People) Teacher() {
fmt.Println("this people is a teacher")
}

func (p *People) Student() {
fmt.Println("this people is a student")
}

func (p *People) Driver() {
fmt.Println("this people is a driver")
}

func (p *People) Police() {
fmt.Println("this people is a police")
}

func main() {
p := &People{}
p.Teacher()
p.Student()
p.Driver()
}

这样加在小项目中很方便也很直观,但是对于开闭原则来说他已经破环了源代码的结构,因此我们需要换个思路设计代码:

开闭原则下的代码:

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
package main

import "fmt"

// 开闭原则

type People interface {
ZhiYe()
}

type Student struct{}

func (s Student) ZhiYe() {
fmt.Println("学生")
}

type Teacher struct{}

func (t Teacher) ZhiYe() {
fmt.Println("老师")
}

type Police struct{}

func (p Police) ZhiYe() {
fmt.Println("警察")
}

func main() {
var people People
people = Student{}
people.ZhiYe()

people = Teacher{}
people.ZhiYe()

people = Police{}
people.ZhiYe()
}

// go run main.go
学生
老师
警察

个人感觉开闭原则更像是单一职责原则的进一步优化

但是个人感觉这样子的写法对于小型一点的项目没啥用,个人更喜欢直接加方法哈哈哈