软件编程
位置:首页>> 软件编程>> C#编程>> C#面向对象设计原则之接口隔离原则

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

作者:.NET开发菜鸟  发布时间:2022-07-22 21:02:58 

标签:C#,接口,隔离,原则

接口隔离原则(ISP)

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

示例1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 接口隔离原则
{
   /// <summary>
   /// 定义一个学习电脑的接口
   /// </summary>
   public interface ILearnComputer
   {
   }

/// <summary>
   /// 定义一个上网电脑的接口
   /// </summary>
   public interface INetComputer
   { }

/// <summary>
   /// 定义一个学生电脑类,实现学习电脑的接口和上网电脑的接口
   /// </summary>
   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 接口隔离原则
{
   /// <summary>
   /// 定义一个学习电脑的接口
   /// </summary>
   public interface ILearnComputer
   {
   }

/// <summary>
   /// 定义一个上网电脑的接口
   /// </summary>
   public interface INetComputer
   { }

/// <summary>
   /// 定义一个学生电脑的抽象类,实现学习电脑的接口和上网电脑的接口
   /// </summary>
   public abstract class StudentComputer : ILearnComputer, INetComputer
   {
       public abstract void Learn();

public abstract void NetPlay();
   }
}

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

代码下载链接:点此下载

来源:https://www.cnblogs.com/dotnet261010/p/7351538.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com