Liskov Substitution Principle

Just look at the more abstract concepts, first examples. An example of violating the Liskov substitution principle, and an example of obeying the Richter substitution principle.

// 绘制图形
void drawShape(Shape shape) {
    
    
	if (shape.type == Shape.Circle) {
    
    
		drawCircle((Circle) shape);
	} else if (shape.type == Shape.Square) {
    
    
		drawSquare((Square) shape);
	} else {
    
    
		......
	}
	// 新增图像必需要修改drawShape方法,添加if判断来支持新的图形,违反了开闭原则
	// 同样是因为新增图像必需要修改drawShape方法,违反了里氏替换原则
}
// 在基类Shape中定义一个抽象方法
public abstract Shape {
    
    
	public abstract draw();
}
// 然后修改drawShape方法
void drawShape(Shape shape) {
    
    
	shape.draw();
}
// 这样优化使drawShape既满足开闭原则又满足里氏替换原则。在使用基类的这个方法中可以用子类替换,程序正常运行(这就是里氏替换设计原则)

Understanding
In a scenario where one piece of business logic needs to depend on another piece of business logic, it does not directly depend on the specific implementation, but on the interface method or abstract method of its base class,
BUT. . . . . In the execution of business logic, subclasses can be used to replace the base class. This design principle is called the Richter substitution principle.
In fact, the principle of the Richter substitution principle is to use polymorphism. In layman's terms, multiple implementations of an interface or abstract class are polymorphic. Interface-oriented programming can be achieved through polymorphism, and specific implementation classes can be bound when the program is running, so that associations can be achieved without direct coupling between classes.
The Richter substitution principle is a design principle of class inheritance relationship

One sentence summary: the subclass must be able to replace the base class, and does not affect the use of the base class user

Guess you like

Origin blog.csdn.net/feifeixiongxiong/article/details/113006918