Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

oop - Interface Segregation Principle- Program to an interface

I was reading about SOLID and other design principles. I thought ISP was the same as "Program to an interface, not an implementation". But it looks like these are different principles?

Is there a difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Robert Martin has a very good explanation of Interface segregation principle (ISP), in his book "UML for Java Programmers". Based on that, I don't think ISP is about an interface being "focused" on one logical, coherent group of things. Because, that goes without saying; or, at least it should go without saying. Each class, interface or abstract class should be designed that way.

So, what is ISP? Let me explain it with an example. Say, you have a class A and a class B, which is the client of class A. Suppose, class A has ten methods, of which only two are used by B. Now, does B need to know about all ten methods of A? Probably not - the principle of Information hiding. The more you expose, the more you create the chance for coupling. For that reason, you may insert an interface, call it C, between the two classes (segregation). That interface will only declare the two methods that are used by B, and B will depend on that Interface, instead of directly on A.

So now,

class A {
  method1()
  method2()
  // more methods
  method10()
}

class B {
   A a = new A()
}

will become

interface C {
  method1()
  method2()
}

class A implements C{
  method1()
  method2()
  // more methods
  method10()
}

class B {
  C c = new A()      
}   

This, prevents B from knowing more than it should.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...