单一职责原则
类的职责单一,对外只提供一种功能,引起类的变化的原因应该只有一个
这个原则很好理解,也就是 逻辑上的单一性保证逻辑清晰
下面有一个案例,我们有两个穿衣服方式
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
| package main
import "fmt"
type Clothes struct{}
func (c *Clothes) Work() { fmt.Println("工作的装扮") }
func (c *Clothes) OnShop() { fmt.Println("购物的装扮") }
func main() { c := &Clothes{}
fmt.Println("工作中......") c.Work()
fmt.Println("购物中......") c.OnShop() }
工作中...... 工作的装扮 购物中...... 购物的装扮
|
那么如果我们修改一下代码:
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
| package main
import "fmt"
type Clothes struct{}
func (c *Clothes) Work() { fmt.Println("工作的装扮") }
func (c *Clothes) OnShop() { fmt.Println("购物的装扮") }
func main() { c := &Clothes{}
fmt.Println("工作中......") c.Work()
fmt.Println("购物中......") c.Work() }
工作中...... 工作的装扮 购物中...... 工作的装扮
|
我们发现我们换了方法后,依旧输出了相同的内容,而当后面的人去看这个代码的时候就会一脸蒙蔽—-为什么购物中下面的方法是 c.Work()
下面用单一职责原则改进一下代码
简单来说就是一个struct一个特定的方法:
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
| package main
import "fmt"
type ShopClothes struct{}
func (s *ShopClothes) Style() { fmt.Println("工作的装扮") }
type WorkClothes struct{}
func (w *WorkClothes) Work() { fmt.Println("工作的装扮") }
func main() { shop := new(ShopClothes) shop.Style()
work := new(WorkClothes) work.Work() }
工作的装扮 工作的装扮
|
改进过的代码中虽然输出的内容还是一样的,但是从代码结构上就可以很轻易的理清楚逻辑
哪个是购物的装扮,哪个是工作的装扮,代码清晰度可见一斑