C语言
主页 > 软件编程 > C语言 >

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

2022-03-02 | 秩名 | 点击:

接口隔离原则(ISP)

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

示例1:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

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
相关文章
最新更新