设计模式七大原则之接口隔离原则

接口隔离原则:客户端不应该依赖它不需要的接口;一个类对另一个类的依赖应该建立在最小的接口上。

接口隔离不应该继承臃肿的接口,只依赖需要的接口,接口必须实现单一职责原则,

举个简单的例子:

 1     public class B : A
 2     {
 3         public void Method1()
 4         {
 5             Console.WriteLine("需要用到方法1");
 6         }
 7 
 8         public void Method2()
 9         {
10             throw new NotImplementedException();
11         }
12 
13         public void Method3()
14         {
15             Console.WriteLine("需要用到方法3");
16         }
17 
18         public void Method4()
19         {
20             Console.WriteLine("需要用到方法4");
21         }
22 
23         public void Method5()
24         {
25             throw new NotImplementedException();
26         }
27     }
28 
29     public class C : A
30     {
31         public void Method1()
32         {
33             Console.WriteLine("需要用到方法1");
34         }
35 
36         public void Method2()
37         {
38             Console.WriteLine("需要用到方法2");
39         }
40 
41         public void Method3()
42         {
43             throw new NotImplementedException();
44         }
45 
46         public void Method4()
47         {
48             throw new NotImplementedException();
49         }
50 
51         public void Method5()
52         {
53             Console.WriteLine("需要用到方法5");
54         }
55     }
56 
57 
58 
59     public interface A
60     {
61         void Method1();
62         void Method2();
63         void Method3();
64 
65         void Method4();
66         void Method5();
67 
68     }

        从上面的例子我们可以看到,B需要用到A接口的Method1,Method3,Method4方法,C需要用到A接口的Method1,Method2,Method5方法,B和C类继承的A接口都有不需要用到的接口方法,造成臃肿。

        根据接口隔离原则,当一个接口太大时,需要将它分割成一些更细小的接口,使用该接口的客户端仅需制定与之相关的方法就可以了。每一个接口应该承担一种相对独立的角色。这里的接口有两种不同的含义:一种是指一个类型所具有的方法特征的集合,仅仅是一种逻辑上的抽象;另一种是指某种语言具体的接口定义,有严格的定义和结构,比如Java语言中的interface。对于这两种不同的含义,ISP的表达方式以及含义都有所不同。

我们来对上面的例子通过实现接口隔离原则进行二次改造:

 1     public class B : A1
 2     {
 3         public void Method1()
 4         {
 5             Console.WriteLine("需要用到方法1");
 6         }
 7 
 8         public void Method3()
 9         {
10             Console.WriteLine("需要用到方法3");
11         }
12 
13         public void Method4()
14         {
15             Console.WriteLine("需要用到方法4");
16         }
17  
18     }
19 
20     public class C : A2
21     {
22         public void Method1()
23         {
24             Console.WriteLine("需要用到方法1");
25         }
26 
27         public void Method2()
28         {
29             Console.WriteLine("需要用到方法2");
30         }
31 
32         public void Method5()
33         {
34             Console.WriteLine("需要用到方法5");
35         }
36     }
37 
38 
39 
40     public interface A
41     {
42         void Method1();
43      
44     }
45 
46     public interface A1:A
47     {
48         void Method3();
49         void Method4();
50     }
51 
52 
53     public interface A2 : A
54     {
55         void Method2();
56         void Method5();
57     }

 

     

 

posted @ 2019-11-28 21:24  虔城墨客  阅读(239)  评论(0编辑  收藏  举报