C#面向对象设计原则之接口隔离原则

这篇文章介绍了C#面向对象设计原则之接口隔离原则,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

接口隔离原则(ISP)

定义:使用多个专门的接口比使用单一的总接口要好。即不要把鸡蛋都放到一个篮子里。
好处:比较灵活、方便,不想实现的或不用实现的可以不实现。
解释说明:
大部分人都喜欢用一个接口把需要用到的方法全部声明出来,但是ISP建议我们使用多个专门的接口比使用单一的总接口要好,也就是一个接口里的方法多的话,实现起来不是很方便。

示例1:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 接口隔离原则 { ///  /// 定义一个学习电脑的接口 ///  public interface ILearnComputer { } ///  /// 定义一个上网电脑的接口 ///  public interface INetComputer { } ///  /// 定义一个学生电脑类,实现学习电脑的接口和上网电脑的接口 ///  public class StudentComputer : ILearnComputer, INetComputer { public void Learn() { Console.WriteLine("学习"); } public void NetPlay() { Console.WriteLine("上网"); } } }

在上面的示例代码中,定义了两个接口,一个具体的电脑类实现了两个接口。如果只想上网,只实现上网的接口就可以;如果只想学习,则只实现学习的接口就可以。

示例2:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 接口隔离原则 { ///  /// 定义一个学习电脑的接口 ///  public interface ILearnComputer { } ///  /// 定义一个上网电脑的接口 ///  public interface INetComputer { } ///  /// 定义一个学生电脑的抽象类,实现学习电脑的接口和上网电脑的接口 ///  public abstract class StudentComputer : ILearnComputer, INetComputer { public abstract void Learn(); public abstract void NetPlay(); } }

具体操作时,抽象类和接口搭配进行使用。使用抽象类实现接口,在调用的时候使用抽象类进行变量的声明。

代码下载链接:点此下载

到此这篇关于C#面向对象设计原则之接口隔离原则的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持0133技术站。

以上就是C#面向对象设计原则之接口隔离原则的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程