This is the 21st day of my participation in the August More Text Challenge

Richter’s substitution principle

The three main characteristics of objects are encapsulation, inheritance and polymorphism

Inheritance: Improves code reusability and extensibility (as illustrated by the example of the open and closed principle mentioned in the previous article), but is more inheritance better? Of course not, once you have inheritance, you can get all the methods and attributes of the parent class (non-private), which is somewhat constrained by the subclass; At the same time, if the parent class needs to be modified, it may have an impact on the child class (enhanced coupling);

The Richter substitution principle can avoid the disadvantages of inheritance to some extent. What is the Richter substitution principle?

public class A { public int fun1(int a,int b){return a-b; } } public class B extends A{ public int fun1(int a,int b){return a+b; } public int fun2(int a,int b){return fun1(a,b)+8; } } public class Test { public static void main(String[] args) { A a = new A(); System. The out. Println (" 11-3 = "+ a.f un1 (11, 3)); System. The out. Println (" 1-8 = "+ b. un1 (1, 8)); B b = new B(); System. The out. Println (" 11-3 = "+ b. un1 (11, 3)); / / 11-3 System. Intention here is to want to seek out the println (" 1-8 = "+ b. un2 (1, 8)); }}Copy the code

Class B inherits the fun1 method of A, originally intended to find 11-3 in B.Fun1 (11,3), but modified the original method edge of class A to find 11+3. We share the inheritance from above, once the parent class is modified, it will affect the subclass. If more inheritance, the result is unimaginable. But in the programming process can consider the Li substitution principle

That is, a subclass can extend the functionality of the parent class, but cannot change the functionality of the parent class. When using inheritance, try not to override methods of a parent class in a subclass. As we can see from the inner substitution principle, inheritance actually increases the coupling between classes, and in this case, we can solve the problem through aggregation, composition, and dependency, where appropriate. Following the above ideas, we can modify the code:

Public class Base{} public class A extends Base{public int fun1(int A,int b){return A -b; } } public class B extends Base{ private A a = new A(); public int fun1(int a,int b){return a+b; } public int fun2(int a,int b){return fun1(a,b)+8; } public int fun3(int a,int b){return this.a.fun1(a,b); }}Copy the code

Fun1, fun2, fun2, fun1, fun2, fun1, fun2, fun1, fun2, fun2

Interface Isolation Principle

The basic idea is that the dependency of one class on another should be based on the smallest interface. Look as shown in figure:

The principle of interface isolation is easy to understand. It is to divide a large interface into multiple smaller interfaces and divide the dependency on the interfaces to the smallest interface