Interface Segregation Principle- Program to an interface

前端 未结 6 667
无人及你
无人及你 2020-12-01 01:05

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 differen

6条回答
  •  伪装坚强ぢ
    2020-12-01 01:44

    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.

提交回复
热议问题