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

接口隔离原则(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 }

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

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

原文地址:https://www.cnblogs.com/dotnet261010/p/7351538.html