The Dimit principle, the principle of opening and closing, and the principle of composite reuse (combined understanding of text codes) of the seven design principles of java

The Dimit principle, the principle of opening and closing, and the principle of composite reuse of the seven design principles of java
---combined understanding of text codes

What are the seven design principles?

  • Single responsibility principle
  • Interface isolation principle
  • Dependence inversion (inversion) principle
  • Richter substitution principle
  • Principle of opening and closing
  • Dimit's Law
  • Synthetic reuse principle

Usually everyone understands the first six, and there is no synthetic reuse principle

Why use the seven design principles?

  • Code reusability (the same code does not need to be written multiple times);
  • Readability (standardization of programming, easy for other programmers to read and understand);
  • Extensibility (when new functions need to be added, it is very convenient, also called maintainability);
  • Reliability (when we add new functions, it will not affect the original functions);
  • Make the program present the characteristics of high cohesion and low coupling

Dimit principle

Definition of Dimit Principles:

  • One object should have minimal knowledge of other objects
  • The closer the relationship between class and class, the greater the degree of coupling
  • Dimit’s rule has a simpler definition: only communicate with direct friends

Dimit’s Rule is also called the Least Knowing Principle , that is, the less a class knows about the classes it depends on, the better . That is to say, no matter how complicated the dependent class is, try to encapsulate the logic inside the class and provide it to the outside world. Public method, no information leakage

What is a direct friend:

In a class: global variables, return values, parameter passing are called direct friends,

Local variables are called strange friends

Look at a piece of easy-to-understand code:

public class A {
    
    }
public class B {
    
    }
public class C {
    
    }
public class D {
    
    }
public class E {
    
    }

public class B {
    
    
   public A mA;

   public C getC(){
    
    
       return null;
   }

   public void showD(){
    
    
       D d = new D();
   }

   public void setA(E e){
    
    

   }
}

In category B:

  • public A mA; global variable
  • public C getC(){ return value
    return null;
    }
  • public void showD(){ local variable (violating Dimit's principle)
    D d = new D();
    }
  • public void setA(E e){} parameter passing

Here A, C, E are the direct friends of B, and D is the strange friend of B

Code for failure to comply with Dimit's principle:

public class Student{
    
    
    String name = "";
    public Student(String name) {
    
    
        this.name = name;
    }
}

public class StudentManager {
    
    
    public void getStudentNumber(Student student){
    
    
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
    
    
            list.add(student.name+i);
            Log.i("dimiter:","现在是第 "+i+"个学生,名字为: "+list.get(i));
        }
        Log.i("dimiter:","总共有 "+list.size()+"个学生 ");
    }
}

//使用代码:
//迪米特原则
StudentManager studentManager = new StudentManager();
studentManager.getStudentNumber(new Student("张三"));

analysis:

  • Student has neme parameter (student name)
  • Student Manager (StudentManager) creates 10 students and outputs student names

Violation of Dimit's principle code:

代码图(1.1):


Why violate the Dimit principle:

The Demeter principle is also called the least-know principle. First, you must understand:

  • What is the least-know principle , which means: the coupling between two classes is particularly low, and the coupling is particularly low, which means that there is very little interaction between them, that is , the less a class knows about the classes it depends on, the better , in 代码图(1.1)this example It can be seen that the StudentManager() class creates 10 student names for the Studnet() class. Know too much

  • Do not disclose information to the outside:代码图(1.1) the code in the red box should be completed inside Student(), and then directly called by StudentManager()

In plain English explanation : StudentManager () requires all students, the right should be Student () it all students directly to StudentManager (), rather than to a Student () objects, let StudentManager () yourself to calculate all students in vernacular point It is : I ask you what you want, give me what you want, don't let me calculate (一个类对自己依赖的类知道的越少越好), don't let me know your things(不对外泄露信息)

It's still more convoluted, just take a look at the code that obeys Dimit's principle and it's straightforward~

Observe the Dimit principle:

public class Student{
    
    
    String name = "";///学生名字
    
     ///用来存储所有学生名字
    ArrayList<String> mList = new ArrayList<>();

    public Student(String name) {
    
    
        this.name = name;
    }

     /// 遵守迪米特原则 创建10个学生
    public List<String> newStudentName(){
    
    
        for (int i = 0; i < 10; i++) {
    
    
            mList.add(name+i);
            Log.i("dimiter:","现在是第 "+i+"个学生,名字为: "+mList.get(i));
        }
        return mList;
    }
}

public class StudentManager {
    
    
    public void getStudentNumber(Student student) {
    
    
        /// 遵守迪米特原则
        List<String> list = student.newStudentName();
        Log.i("dimiter:", "总共有 " + list.size() + "个学生 ");
    }
}

//使用代码:
//迪米特原则
StudentManager studentManager = new StudentManager();
studentManager.getStudentNumber(new Student("张三"));

Student() creates 10 students, and then gives StudentManager() compliance:

The Least Know (Dimit) Principle A class knows as little as possible about the classes it depends on and does not disclose information.

One object should have minimal knowledge of other objects

The least understanding here refers to 10 Student() students

I only know you have 10 students, no matter how your 10 students came

效果图(2.1):

Principle of opening and closing

Definition of opening and closing principle:

  • The principle of opening and closing is the most basic and important design principle in programming
  • A software entity such as class, module and method should be open to extension (to the provider), closed to modification (to the user), use abstraction to construct the framework, and use implementation to extend the details (details refer to the implementation code)
  • When the software requirements change, try to achieve the change by expanding the behavior of the software entity, rather than by modifying the existing code to achieve the change
  • Comply with other principles, and the purpose of using design patterns is to comply with the principle of opening and closing

Code that does not comply with the opening and closing principle:

//形状类型
public abstract class Shape {
    
    
    /**
     * 用来判断类型
     * 1:Circular 圆形
     * 2:Rectangle 矩形
     */
    int type;
}

//圆形
public class Circular extends Shape {
    
    
    public Circular() {
    
    
        type = 1;
    }
}

//矩形
public class Rectangle extends Shape {
    
    
    public Rectangle() {
    
    
        type = 2;
    }
}
//开闭原则Manager类 
public class OpenManager {
    
    
    public void showShape(Shape shape){
    
    
        if (shape .type == 1) {
    
    
            drawCircular(shape);
        }else if (shape.type == 2){
    
    
            drawRectangle();
        }
    }

    private void drawRectangle() {
    
    
        Log.i("Open","创建矩形 ");
    }
    private void drawCircular(Shape shape) {
    
    
        Log.i("Open","创建圆形 ");
    }
}

//使用代码:
 //开闭原则
OpenManager openManager = new OpenManager();
openManager.showShape(new Circular());//创建圆
openManager.showShape(new Rectangle());//创建矩形 

效果图(2.2):

Why did not follow the opening and closing principle:

The most critical definition of the opening and closing principle is:

Expand open (to the provider), close to modification (to the user), use abstraction to build the framework, and use implementation to expand the details (details refer to the implementation code)

What if I want to add a new triangle now?

Is it written like this?

public class Triangle  extends Shape{
    
    
    public Triangle() {
    
    
        type = 3;
    }
}

public class OpenManager {
    
    
    public void showShape(Shape shape){
    
    
        if (shape .type == 1) {
    
    
            drawCircular();//创建圆
        }else if (shape.type == 2){
    
    
            drawRectangle();//创建矩形
        }else if(shape.type == 3){
    
    
            drawTriangle();//创建三角形
        }
    }
    private void drawTriangle() {
    
    
        Log.i("Open","创建三角形 ");
    }
}
//使用代码
//开闭原则
OpenManager openManager = new OpenManager();
openManager.showShape(new Circular());
openManager.showShape(new Rectangle());
openManager.showShape(new Triangle());

效果图(2.3):


This writing not only easily leads to code conflicts in the process of modification, but also judges by if else

What if I have 100 graphics? Will it be judged 100 times?

if lese if lese if lese if lese if lese if lese if lese if lese if lese if lese…?

This write error rate is too high, and it has not been complied with to expand and open, modify and close

Observe the opening and closing principle code:

public abstract class Shape {
    
    
    public abstract void showShape();
}

public class Circular extends Shape {
    
    
    @Override
    public void showShape() {
    
    
        Log.i("Open","创建圆形 ");
    }
}

public class Triangle  extends Shape{
    
    
    @Override
    public void showShape() {
    
    
        Log.i("Open","创建三角形 ");
    }
}

public class Rectangle extends Shape {
    
    
    @Override
    public void showShape() {
    
    
        Log.i("Open","创建矩形 ");
    }
}

public class OpenManager {
    
    
    public void showShape(Shape shape){
    
    
        //遵守开闭原则
        shape.showShape();
    }
}

//使用代码:
//开闭原则
OpenManager openManager = new OpenManager();
openManager.showShape(new Circular());
openManager.showShape(new Rectangle());
openManager.showShape(new Triangle());

analysis:

  • It can be seen that even if a new triangle class (Triangle) is added now, it can be drawn as long as it inherits from Shape, and there is no if else to judge, the code logic is very clear
  • This is the real expansion development, and the modification is closed . Even if I am adding an oval now, I need to inherit from Shape() and output it.
public class Ellipse  extends Shape{
    
    
    @Override
    public void showShape() {
    
    
        Log.i("Open","我是新创建的椭圆形哦");
    }
}
 //开闭原则
OpenManager openManager = new OpenManager();
openManager.showShape(new Circular());
openManager.showShape(new Rectangle());
openManager.showShape(new Triangle());
openManager.showShape(new Ellipse());//创建椭圆形

It is similar to the dependency inversion principle , except that the dependency inversion principle is implemented through interfaces, and the opening and closing principle is implemented through abstraction.

Synthetic reuse principle

Definition of composite reuse principle:

When the software is reused, try to use the combination or aggregation relationship to achieve it first, and then consider using the inheritance relationship to achieve it.


Generally, class reuse is divided into inheritance reuse and composite reuse. Although inheritance reuse has the advantages of simplicity and easy implementation, it also has the following disadvantages :

  • Inheritance reuse destroys the encapsulation of the class. Because inheritance exposes the implementation details of the parent class to the child class, and the parent class is transparent to the child class, this kind of reuse is also called "white box" reuse.
  • The degree of coupling between the child class and the parent class is high . Any change in the implementation of the parent class will result in changes in the implementation of the subclass, which is not conducive to the expansion and maintenance of the class.
  • It limits the flexibility of reuse . The implementation inherited from the parent class is static and has been defined at compile time, so it is impossible to change at runtime

Translation in vernacular:
Try not to inherit. If you inherit, the subclass and the parent class are highly coupled, and the parent class is transparent to the subclass. It is not conducive to maintenance. If you have to reuse it, you can use the combination/aggregation method.

It doesn't matter if you don't understand composition/aggregation, I will introduce the relationship between classes in detail in the next chapter!

The core idea of ​​design principles

  • Find the changes that may be needed in the application, isolate them, and don't mix them with code that does not need to change.
  • Interface-oriented programming, not implementation-oriented programming.
  • Work hard for the design of loose coupling between interactive objects.
  • Expand open (to the provider), close to modification (to the user), use abstraction to build the framework, and use implementation to expand the details (details refer to the implementation code)

Dimit (least known) principle code

Principle of opening and closing

Summary of design patterns:

  • Open and close (OCP) principle : expand open, modify and close
  • Interface isolation principle : the dependency between classes should be established on the smallest interface
  • Single responsibility principle : one class is responsible for one responsibility, not one class is responsible for one responsibility
  • Dependence inversion principle : interface-oriented programming
  • Richter substitution principle : When inheriting, try not to override the method of the parent class in the subclass. If you have to use it, you can use aggregation, composition, and dependency to solve the problem, and don't modify the method of the parent class!
  • Dimit (least known) principle : Only communicate with direct friends, the less a class knows about the classes it depends on, the better, and no information is leaked.
  • The principle of composite reuse : try to use the relationship of composition or aggregation to achieve, and then consider inheritance

you may also like:

Go to the design pattern/design principle catalog page

Originality is not easy, remember to like it~

Guess you like

Origin blog.csdn.net/weixin_44819566/article/details/112257643