Definition: An object should maintain a minimal understanding of other objects.
The problem: The closer the relationship between classes and classes, the greater the degree of coupling, the greater the impact on another class when a class changes.
Solution: Reduce the coupling between classes and classes as much as possible.
Since we began to contact programming, we know the general principles of software programming: low coupling, high cohesion. Whether the process-oriented programming or object-oriented programming, only to make the coupling between each module as low as possible to improve the code reuse rate. The advantages of low coupling are self-evident, but how can programming achieve low coupling? That's exactly what the Dimitri law is going to do.
The Dimitri rule, also called the least known principle, was first proposed by Ian Holland of the American Northeastern University in 1987. In layman's terms, it is a class that knows less about the classes it relies on. In other words, for the dependent classes, no matter how complex the logic is, try to encapsulate the logic within the class as much as possible and not disclose any information outside the public method provided. The Dimitri Law also has a simpler definition: only communicate with direct friends. First, explain what a direct friend is: Each object has a coupling relationship with other objects, so long as the two objects are coupled, we say the two objects are friends. There are many ways of coupling, dependence, association, combination, aggregation and so on. Among them, we call the class in the member variable, method parameter, method return value as the direct friend, and the class appearing in the local variable is not a direct friend. In other words, unfamiliar classes are best not to appear as local variables inside the class.
Here is an example of a violation of the Dimitri principle:
public class Teacher {public
void teach (Classes Classes) {
classes.getStudents.getScore.show ();
}
}
What are the problems? Coupling is too high.
1. The score class may be canceled in the Student class.
2. The show method of the score class may also be deleted.
Student classes, score classes are unfamiliar to you, and you may not know when they change.
We can modify it into:
public class Teacher {public
void teach (Classes Classes) {
classes.showscore ();
}
}
public class Classes {public
void Showscore (Student Student) {
student.showscore ();
}
}
public class Student {
Score Score;
public void Showscore () {
score = new score ();
Score.show ();
}
Summarize:
1. The advantage of the Dimitri rule is to reduce coupling between classes.
2. The disadvantage is that there will be more small ways to make the system more messy, and communication efficiency will be reduced.
3. Applications in Design Patterns: Façade mode (façade pattern) and intermediary mode (mediator pattern).