2.0 - Design Patterns seven principles of software architecture design - Interface Segregation Principle

Interface segregation principle (Interface Segregation Principle, ISP) refers to the use of a plurality of dedicated interfaces, interfaces without using the single general, the client should not rely on it does not interface. The principles that guide us in the design of the interface should note the following: 1, a class dependent on a class should be based on a minimum of interfaces. 2, the establishment of a single interface, do not create bloated interface. 3, an interface as possible refinement process to minimize interface (not better, must be appropriate). Interface segregation principle in line with our design philosophy often say high cohesion and low coupling, so that the class has good readability, scalability and maintainability. We have to think about the design of the interface of the time, spend time, to consider the business model, including with the potential to change the place of occurrence need to do some pre-judgment. So, for abstract understanding of the business model it is very important.

Let's look at the code section of the animal

IAnimal Interface:

public interface IAnimal {
    void eat();
    void fly();
    void swim();
}

Bird class implementation:

public class Bird implements IAnimal {
    @Override
    public void eat() {}
    @Override
    public void fly() {}
    @Override
    public void swim() {}
}

Dog class implementation:

public class Dog implements IAnimal {
    @Override
    public void eat() {}
    @Override
    public void fly() {}
    @Override
    public void swim() {}
}

As can be seen, Bird's swim () method may only be empty, Dog's fly () method is obviously impossible. At this time, we focused on different animal behavior to design different interfaces were designed IEatAnimal, IFlyAnimal and ISwimAnimal interfaces, look at the code: IEatAnimal Interface:

public interface IEatAnimal {
    void eat();
}

IFlyAnimal Interface:

public interface IFlyAnimal {
    void fly();
}

ISwimAnimal Interface:

public interface ISwimAnimal {
    void swim();
}

Dog only achieved IEatAnimal and ISwimAnimal interfaces:

public class Dog implements ISwimAnimal,IEatAnimal {
    @Override
    public void eat() {}
    @Override
    public void swim() {}
}

Comparison of both the class diagram view of still very clear:

Guess you like

Origin blog.csdn.net/madongyu1259892936/article/details/93465850