单一职责
官方定义:应该有且仅有一个原因引起类的变更
通常来说就是一个类最好负责一件事情,就一个类而言,就应该仅有一个引起它变化的原因,我们写编程的时候很自然的给一个类增加各种功能,属性、字段什么的、那么将来维护的时候就会出现很多问题,我们添加功能或者别的任何需求都要改动这个类,缺乏灵活性。
自己理解:我觉得单一职责好理解,就是不好运用,因为需要对软件有很强的分析能力,就比如做一个软件,做这些功能的时候,你就要把这些功能职责的划分的很明确。
实例:生产商生成手机就要实现相应的接口和方法,例如:CPU、内存,实现打电话、接电话的功能.......
/// <summary>
/// 手机属性接口
/// </summary>
public interface Imobilephonebasep
{
//运行内存
string Neicun { get; set; }
//存储内存
string Cunchu { get; set; }
//CPU
string Cpu { get; set; }
//大小
string Size { get; set; }
}
/// <summary>
/// 手机扩展属性
/// </summary>
public interface ImobilephonebasepExtend
{
//摄像头像素
string px { get; set; }
}
/// <summary>
/// 手机功能接口
/// </summary>
public interface ImobilephonebaseFunc
{
//手机充电
void Chongdian(ElectricSource ElectricSource);
//打电话
void DaDianHua();
//接电话
void JieDianHua();
}
/// <summary>
/// 手机功能扩展接口
/// </summary>
public interface ImobilephonebaseFuncExecten
{
//上网
void Intenet();
//移动办公
void MOA();
//玩游戏
void palyGame();
}
如果我们不用扩展属性、扩展方法的话,设想一下:虽然现在很多人使用智能机,有拍照、登扣扣这些功能,你直接全部定义在一个接口里面,那么生产老人机的时候也要实现这种接口就显得不那么合理。
实现类:
/// <summary> /// 手机基本属性实现 /// </summary> public class PhoneProperty : Imobilephonebasep { public string Cpu { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string Cunchu { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string Neicun { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string Size { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// 手机扩展属性实现 /// </summary> public class PhoneExetendProperty : ImobilephonebasepExtend { public string px { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } /// <summary> /// 手机基础功能实现 /// </summary> public class PhoneFunc : ImobilephonebaseFunc { public void Chongdian(ElectricSource ElectricSource) { throw new NotImplementedException(); } public void DaDianHua() { throw new NotImplementedException(); } public void JieDianHua() { throw new NotImplementedException(); } } /// <summary> /// 手机扩展功能实现 /// </summary> public class PhoneExetendFunc : ImobilephonebaseFuncExecten { public void Intenet() { throw new NotImplementedException(); } public void MOA() { throw new NotImplementedException(); } public void palyGame() { throw new NotImplementedException(); } }
这样的话相对来说合理一点,或许会有更完美的解决,就需要根据需求分析,建立对应的属性、方法
浙公网安备 33010602011771号