# 单一职责原则

## 参考文档：

***24种设计模式介绍与6大设计原则.pdf*** 链接: <https://pan.baidu.com/s/1WnFwH9_o29Z48UpQyadiPA> 密码: i238

## 概述

单一职责原则（SRP：Single responsibility principle）又称单一功能原则，面向对象五个基本原则（SOLID）之一。它规定一个类应该只有一个发生变化的原因。该原则由罗伯特·C·马丁（Robert C. Martin）于《敏捷软件开发：原则、模式和实践》一书中给出的。马丁表示此原则是基于[汤姆·狄马克](https://baike.baidu.com/item/汤姆·狄马克/284013)(Tom DeMarco)和Meilir Page-Jones的著作中的[内聚性](https://baike.baidu.com/item/内聚性/4973441)原则发展出的。

所谓职责是指类变化的原因。如果一个类有多于一个的动机被改变，那么这个类就具有多于一个的职责。而单一职责原则就是指一个类或者模块应该有且只有一个改变的原因。

一个类，只有一个引起它变化的原因。应该只有一个职责。每一个职责都是变化的一个轴线，如果一个类有一个以上的职责，这些职责就[耦合](https://baike.baidu.com/item/耦合/2821124)在了一起。这会导致脆弱的设计。当一个职责发生变化时，可能会影响其它的职责。另外，多个职责耦合在一起，会影响

[复用性](https://baike.baidu.com/item/复用性/12719815)。例如：要实现逻辑和界面的分离。

## 原理

如果一个类承担的职责过多，就等于把这些职责[耦合](https://baike.baidu.com/item/耦合/2821124)在一起了。一个职责的变化可能会削弱或者抑制这个类完成其他职责的能力。这种耦合会导致脆弱的设计，当发生变化时，设计会遭受到意想不到的破坏。而如果想要避免这种现象的发生，就要尽可能的遵守单一职责原则。此原则的核心就是[解耦](https://baike.baidu.com/item/解耦)和增强[内聚性](https://baike.baidu.com/item/内聚性/4973441)。

### 问题由来

之所以会出现单一职责原则就是因为在软件设计时会出现以下类似场景：

T负责两个不同的职责：职责P1，职责P2。当由于职责P1需求发生改变而需要修改类T时，有可能会导致原本运行正常的职责P2功能发生故障。也就是说职责P1和P2被[耦合](https://baike.baidu.com/item/耦合/2821124)在了一起。

### 产生原因

没有任何的程序设计人员不清楚应该写出[高内聚低耦合](https://baike.baidu.com/item/高内聚低耦合/5227009)的程序，但是很多[耦合](https://baike.baidu.com/item/耦合/2821124)常常发生在不经意之间，其原因就是：

职责扩散：因为某种原因，某一职责被分化为[颗粒度](https://baike.baidu.com/item/颗粒度/333017)更细的多个职责了。

### 解决办法

遵守单一职责原则，将不同的职责封装到不同的类或模块中。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tuonioooo-notebook.gitbook.io/application-framework/she-ji-mo-shi-pian/she-ji-yuan-ze/dan-yi-zhi-ze-yuan-ze.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
