The Interface Segregation Principle (ISP) refers to the use of multiple specialized interfaces instead of a single master Interface. Clients should not rely on interfaces that they do not need. This principle guides us to consider a few things when designing interfaces:

1. A class’s dependency on a class should be based on the smallest interface.

2, create a single interface, do not create a large and bloated interface.

3, try to refine the interface, the interface method as little as possible (not the less the better, must be moderate).

The interface isolation principle conforms to the commonly referred design idea of high cohesion and low coupling, which makes classes readable, extensible, and maintainable. When we design our interfaces, we need to take the time to think about it, we need to think about the business model,

Including things that might change in the future and some anticipation. Therefore, understanding the business model is very important for abstraction.

public interface IAnimal { 
    void eat();
    void fly();
    void swim();
}
Copy the code
public class Bird implements IAnimal { 

    @Override
    public void eat() {} 
    
    @Override
    public void fly() {} 
    
    @Override
    public void swim() {}
    
}

Copy the code

It can be seen that Bird swim() method may be empty, but Dog fly() method is obviously impossible. At this time, we designed different interfaces for different animal behaviors, respectively designed IEatAnimal, IFlyAnimal and ISwimAnimal interfaces, look at the code

public interface IEatAnimal { 
   void eat();
}

public interface IFlyAnimal {
    void fly();
}

public interface ISwimAnimal {
    void swim();
}


public class Dog implements ISwimAnimal,IEatAnimal { 

    @Override
    public void eat() {}
    
    @Override
    public void swim() {}
    
}


Copy the code

Pay attention to the public number, wonderful continue