Demeter's Law of Java Design Patterns (commonly known as: Principle of Least Knowledge)

 Law of Demeter

Excerpted from: Baidu Encyclopedia

    The Law of Demeter, also known as the Least Knowledge Principle (LKP for short), means that an object should know as little as possible about other objects and not speak to strangers. The English abbreviation is: LoD.

 pattern and meaning

Excerpted from: Baidu Encyclopedia

    The Law of Demeter can be simply stated as: talk only to your immediate friends.  For OOD, it is explained in the following ways: A software entity should interact with other entities as little as possible. Each software unit has minimal knowledge of other units and is limited to those software units closely related to the unit.

The original intention of Demeter's Law is to reduce the coupling between classes . Since each class minimizes its dependencies on other classes, it is easy to make the functional modules of the system independent, and there is no (or very few) dependencies between them.

The Law of Demeter does not expect direct connections between classes. If there is really a need to establish a connection, I hope it can be conveyed through its friend class . Therefore, one of the possible consequences of applying the Law of Demeter is that there are a large number of intermediary classes in the system, and the reason why these classes exist is to transfer the mutual calling relationship between classes - which increases the system's ability to a certain extent. the complexity.

If you are interested, you can study the facade pattern ( Facade ) and the mediator pattern (Mediator) of the design pattern, which are examples of the application of the Law of Demeter.

 Taken from: Dahua Design Patterns

    Law of Demeter, two classes should not interact directly if they don't have to lead directly to each other. If one of the classes needs to call a certain method of another tired, the call can be forwarded through a third party.

    The premise that the Law of Demeter first emphasizes is that in the structural design of the class, each class should reduce the access rights of members, that is, a class wraps its own private state, and does not need to let other classes know the fields or Don't make your behavior public.

    Object-oriented design principles and the three characteristics of object-oriented are not contradictory. The fundamental idea of ​​the Law of Demeter is to emphasize the loose coupling between classes. The weaker the coupling between classes, the more conducive to reuse. If a class in weak coupling is modified, it will not cause fighting to related classes. That is to say, the hiding of information promotes the reuse of software.

advantage

reduce the coupling between objects

Excerpted from Dahua Design Patterns:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325253059&siteId=291194637