一、SRP 基本介绍
-
Single Responsibility Principle(SRP),单一职责原则
- There should never be more than one reason for a class to change.(对于一个类来说,应该有且仅有一个原因使它变更)
- A responsibility is a reason for a class to change,so a class should have single respinsibility to avoid the case that multi-reasons lead to the change of a class.(对于一个类来说,一个职责就是它变更的原因,所以一个类应该具有单一职责来避免多原因导致一个类变更的情况)
-
单一职责原则与内聚性
- 内聚性(Cohesion),Conesion refers to the degree to which the elements inside a module belong together,内聚指的是一个模块的元素属于一个整体(单一职责)的程度。
- Single Responsibility = Increased Cohesion (内聚)
- Multiple Responsibilities = Increased Coupling (耦合)
- Harmful for reusing
- Changing one responsibility will effect the others(职责依赖), the class is friable(脆的) for changes
-
SRP 是一个简单的、指导性的原则,但在实践上很难满足
- 在抽象方面,正确的抽象是 SRP 的关键问题;
- 在实现方面,移动代码(职责)到另一个类(for single responsibility),然后通过调用使用
二、一个不太恰当的例子-Modem
1. 初始设计
接口
public interface IModem{
public void dial(String sno);
public void hangUp();
public void send(String str);
public void recv();
}
实现类
public class Modem{
public void dial(String sno){
// method body
}
public void hangUp(){
// method body
}
public void send(String str){
// method body
}
public void recv(){
// method body
}
}
- Modem 的两个职责
- 连接管理:dial and hangUp
- 交流信息:send and recv
- Modem 两个职责是否应该分开取决于它们是否一起改变
2. 变更设计:抽象方面(abstract aspect)
接口
Connector 接口
public interface IConnector{
public void dial(String sno);
public void hangUp();
}
DataChannel 接口
public interface IDataChannel{
public void send(String str);
public void recv();
}
实现类
public class Connector{
public void dial(String sno){
// method body
}
public void hangUp(){
// method body
}
}
public class DataChannel{
public void send(String str){
// method body
}
public void recv(){
// method body
}
}
public class Modem{
private DataChannel dataChannel;
private Connector connector;
public Modem(DataChannel dataChannel, Connector connector){
this.dataChannel = dataChannel;
this.connector = connector;
}
}
Reference:Software Architecture and Design Patterns Class(sk) of NEU Software College