Interface isolation principle~

The interface isolation principle is a principle in object-oriented design principles. Its core idea is to split a large interface into multiple small interfaces . The client should not rely on interfaces it does not need , that is, the dependence of one class on another class should not Built on a minimal interface, 接口应该具有单一功能it should not contain irrelevant or unnecessary methods in order to improve the flexibility and maintainability of the system. It also requires that the design of the interface should be stable. Once designed, it should not be modified frequently.

Example:

Suppose we define the basic operations of graphics to include drawing, moving, scaling, etc. 对于某些特殊的功能, which are not necessary for every graphics. Then according to the interface isolation principle, we should not define its special functions in the interface that contains the basic operations of graphics, but 写在一个单独的接口中, so that classes that need the functionality can implement the interface

// Shape接口---定义图形的基本操作
 interface Shape {
    
    
    void draw();
    void move(int x, int y);
    void resize(int width, int height);
}
// Rotatable接口---“特殊功能"图形的旋转
  interface Rotatable {
    
    
    void rotate(double angle);
}
// 矩形类不需要实现新添加的旋转功能,不需要实现Rotatable接口
class Rectangle implements Shape {
    
    
    // 实现绘制、移动和缩放方法...
    @Override
    public void draw() {
    
    
        // 绘制矩形...
    }
    @Override
    public void move(int x, int y) {
    
    
        // 移动矩形...
        }
    @Override
    public void resize(int width, int height) {
    
    
        // 缩放矩形...
    }}
// 圆形类---需要实现新添加的旋转功能,需要实现Rotatable接口
public class Circle implements Shape, Rotatable {
    
    
    @Override
    public void draw() {
    
      // 绘制圆形...
        }
    @Override
    public void move(int x, int y) {
    
    
        // 移动圆形...
    }
    @Override
    public void resize(int width, int height) {
    
    
        // 缩放圆形...
    }
    @Override
    public void rotate(double angle) {
    
    
        // 旋转圆形...
    }
}

Guess you like

Origin blog.csdn.net/m0_64365419/article/details/133157361