面向对象设计原则五:接口隔离原则

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

示例1:

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 接口隔离原则
 8 {
 9     /// <summary>
10     /// 定义一个学习电脑的接口
11     /// </summary>
12     public interface ILearnComputer
13     {
14     }
15 
16     /// <summary>
17     /// 定义一个上网电脑的接口
18     /// </summary>
19     public interface INetComputer
20     { }
21 
22     /// <summary>
23     /// 定义一个学生电脑类,实现学习电脑的接口和上网电脑的接口
24     /// </summary>
25     public class StudentComputer : ILearnComputer, INetComputer
26     {
27         public void Learn()
28         {
29             Console.WriteLine("学习");
30         }
31 
32         public void NetPlay()
33         {
34             Console.WriteLine("上网");
35         }
36     }
37 }
复制代码

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

示例2:

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 接口隔离原则
 8 {
 9     /// <summary>
10     /// 定义一个学习电脑的接口
11     /// </summary>
12     public interface ILearnComputer
13     {
14     }
15 
16     /// <summary>
17     /// 定义一个上网电脑的接口
18     /// </summary>
19     public interface INetComputer
20     { }
21 
22     /// <summary>
23     /// 定义一个学生电脑的抽象类,实现学习电脑的接口和上网电脑的接口
24     /// </summary>
25     public abstract class StudentComputer : ILearnComputer, INetComputer
26     {
27         public abstract void Learn();
28 
29         public abstract void NetPlay();
30     }
31 }
复制代码

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

代码下载链接:https://files.cnblogs.com/files/dotnet261010/OO%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99.rar  

posted @   .NET开发菜鸟  阅读(394)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示