Clean Architecture: SRP The Single Responsibility Principle 笔记

1. 什么是单一功能原则 ?

「The Single Responsibility Principle」单一功能原则 是为了解决,不同的人群 (actor)共享同样的代码逻辑,其中一方需要改动,但是不知道其他人群也在使用同样的代码,于是一次改动会影响其他使用这些代码组件的人群。

Clean Architecture 里面是这么定义The Single Responsibility Principle 的

「A module should be responsible to one, and only one, actor」

一个组件,只能对一个有需要改动的群体负责。

Actor可以理解为一个群体,一个,或一些相似的人群,需要用到该组件,有需要对该组件做一些改动。那么这个组件只应当作用在该Actor上,不应该作用在其他Actor上。

2.例子分析

单纯看文字,有点难以理解。用一个反例代码来举例。

假如用Employee 类来定义一家公司的员工,会计部门会调用calculatePay() 来计算员工的工资,hr部门会调用reportsHour() 来计算员工的工作时长。他们都共同共享了算法A用来计算员工的常规工作时长。

Code Example 1:

class Emoloyee 
{
	public void calculatePay() 
	{
		// Algorithm A to count regular hour
	}

	public void reportsHour() 
	{
		// Algorithm A to count regular hour
	}

	public void saveToDb();

}

假如HR部门的工程师需要改动这个算法A,因为HR部门提出了新的计算员工工作时长的标准,但是会计部门目前还不想做相应的变动。 如果HR部门的工程师并不知道会计部门也在使用这个算法,那么HR部门工程师只要改动了该算法,就会影响会计部门的计算,造成会计部门的损失。

那么符合The Single Responsibility Principle 的架构应该是什么样的呢?

我们把不同的Actor分开,每种Actor使用它自己的组件,这样就可以做到不同的Actor business logic互相不影响。



Code Example 2:

abstract class Employee 
{
	abstract calculatePay ()

	abstract reportHours ()

	// Common shared algorithm 
	protected save() 

}

class HR extends Employee 
{
	
	// Define its own algorithm
	calculatePay ()

	// Define its own algorithm
	reportHours() 

}

class Accountant extends Employee 
{
	// Define its own algorithm
	calculatePay ()

	// Define its own algorithm
	reportHours() 
}


class IT extends Employee
{
	// Define its own algorithm
	calculatePay ()

	// Define its own algorithm
	reportHours() 
}

分析:
这样的好处是,不同的人群,如果需要进行该操作,甚至需要做改动,那么能够确保不会影响其他人群的组件。

0 赞 Like

Leave a Reply

Your email address will not be published. Required fields are marked *