设计原则系列文章
必知必会的设计原则——单一职责原则
必知必会的设计原则——开放封闭原则
必知必会的设计原则——依赖倒置原则
必知必会的设计原则——里氏替换原则
概述
1、 客户端不应该依赖它不需要的接口。
2、 一个类对另一个类的依赖应该建立在最小接口上。
3、接口应尽量细分,不要在一个接口中放很多方法。
接口分离和单一原则关系
单一职责:只做一件事 /影响类变化的原因只有一个。目的是你为了高内聚(模块内部的相似程度).
接口隔离:目的是为了低耦合(模块之间的依赖程度要低)。
未使用接口隔离原则的代码
- public interface IScore
- {
- void QueryScore();
- void UpdateScore();
- void AddScore();
- void DeleteScore();
- double GetSumScore();
- double GetAvgScore();
- void PrintScore();
- void SendScore();
- }
- public class Teacher : IScore
- {
- public void AddScore()
- {
- throw new NotImplementedException();
- }
- public void DeleteScore()
- {
- throw new NotImplementedException();
- }
- public double GetAvgScore()
- {
- throw new NotImplementedException();
- }
- public double GetSumScore()
- {
- throw new NotImplementedException();
- }
- public void PrintScore()
- {
- throw new NotImplementedException();
- }
- public void QueryScore()
- {
- throw new NotImplementedException();
- }
- public void SendScore()
- {
- throw new NotImplementedException();
- }
- public void UpdateScore()
- {
- throw new NotImplementedException();
- }
- }
- public class Student : IScore
- {
- public void AddScore()
- {
- throw new NotImplementedException();
- }
- public void DeleteScore()
- {
- throw new NotImplementedException();
- }
- public double GetAvgScore()
- {
- throw new NotImplementedException();
- }
- public double GetSumScore()
- {
- throw new NotImplementedException();
- }
- public void PrintScore()
- {
- throw new NotImplementedException();
- }
- public void QueryScore()
- {
- throw new NotImplementedException();
- }
- public void SendScore()
- {
- throw new NotImplementedException();
- }
- public void UpdateScore()
- {
- throw new NotImplementedException();
- }
- }
复制代码 以上定义成绩接口,接口里面包含的方法分别为查询成绩,添加成绩、修改成绩、删除成绩、成就求和,成绩求平均数、打印成绩、发送成绩。Teacher和student类都实现IScore的方法 ,有些方法教师或学生根本没必要实现。
使用接口隔离原则的代码
- public interface ITeacherScore
- {
- void AddScore();
- void DeleteScore();
- double GetSumScore();
- double GetAvgScore();
- void PrintScore();
- void SendScore();
- }
- public class Teacher2 : ITeacherScore
- {
- public void AddScore()
- {
- throw new NotImplementedException();
- }
- public void DeleteScore()
- {
- throw new NotImplementedException();
- }
- public double GetAvgScore()
- {
- throw new NotImplementedException();
- }
- public double GetSumScore()
- {
- throw new NotImplementedException();
- }
- public void PrintScore()
- {
- throw new NotImplementedException();
- }
- public void SendScore()
- {
- throw new NotImplementedException();
- }
- }
- public interface IStudentScore
- {
- void QueryScore();
- void PrintScore();
- }
- public class Student2 : IStudentScore
- {
- public void PrintScore()
- {
- throw new NotImplementedException();
- }
- public void QueryScore()
- {
- throw new NotImplementedException();
- }
- }
复制代码 以上代码使用接口隔离原则后,接口职责很清晰,定义的接口不再像之前的大而全。
总结
接口隔离原则和单一职责原则很像,关于二者之间的关系在开头概述里面已经描述,如有疑问欢迎与我交流。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |