面向对象设计模式之单一职责原则(SRP)

一、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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值