Six principles and one rule of design pattern

Java technology debt 2022-06-24 07:28:12 阅读数:570

principlesruledesignpattern


 Insert picture description here

Prompt before reading

The current article has a total of more than 13000 words , It usually takes about ten minutes . Of course, you can browse separately after collecting ...

overview

The six principles and one rule refer to the opening and closing principles 、 Richter's principle of substitution 、 The principle of Dependence Inversion 、 Principle of single responsibility 、 Interface isolation principle 、 Synthetic multiplexing principle 、 Dimitar's law .

this 7 Design principles are the principles that software design patterns must follow as much as possible , Is the basis of design patterns . In the actual development process , Not all code must follow the design principles , It's about human resources 、 Time 、 cost 、 quality , Don't try to be perfect , Follow the design principles in the appropriate scene . This is a balanced choice , Can help us design a more elegant code structure .

Different principles require different emphases , Here we summarize the seven principles of software design patterns in one sentence , As shown in the following table .

Design principles summary Purpose
Opening and closing principle Open to expansion , Turn off for changes Reduce the new risks of maintenance
The principle of Dependence Inversion The high level should not rely on the lower level , Interface oriented programming More conducive to the upgrading and expansion of the code structure
Principle of single responsibility A class does only one thing , The implementation class should be single Easy to understand , Improve the readability of the code
Interface isolation principle One interface does one thing , The interface should be simple Functional decoupling , Hyperpolymerization 、 Low coupling
Dimitar's law Don't know what you shouldn't know , A class should keep a minimum knowledge of other objects , Reduce coupling Only communicate with friends , Don't talk to strangers , Reduce code bloat
Richter's principle of substitution Don't break the inheritance system , Subclass rewriting function changes , The meaning of the parent method should not be affected Prevent the spread of inheritance
Synthetic multiplexing principle Try to use composition or aggregation relationship to achieve code reuse , Use less inheritance Reduce code coupling

actually , There is only one purpose to these principles : Reduce coupling between objects , Increase the reusability of programs 、 Scalability and maintainability .

Memory formula : Access restrictions , Functions should be frugal , Dependency does not allow , Dynamic interface , The parent class should be abstract , Extension does not change .

In programming , We should minimize program functionality , Each class does only one thing . If there are similar functions, add new functions , Then we should make rational use of inheritance . For calls to multiple methods , Be able to use interfaces , At the same time, set the interface function and quantity reasonably . Finally, low coupling and high cohesion between classes .

Opening and closing principle

Definition of opening and closing principle

Opening and closing principle (Open Closed Principle,OCP) By Brandt · meyer (Bertrand Meyer) Put forward , He was in 1988 The book of 《 Object oriented software construction 》(Object Oriented Software Construction) It is proposed that : Software entities should be open to expansion , Turn off for changes (Software entities should be open for extension,but closed for modification), This is the classic definition of the opening and closing principle .

The software entity here includes the following parts :

  1. The modules in the project
  2. Classes and interfaces
  3. Method

Meaning of opening and closing principle : When the requirements of the application change , Without modifying the source code or binary code of the software entity , It can extend the function of the module , Make it meet new needs .

The function of opening and closing principle

The open close principle is the ultimate goal of object-oriented programming , It enables software entities to have certain adaptability and flexibility, as well as stability and continuity . say concretely , Its functions are as follows :

  1. Impact on software testing

    If the software follows the opening and closing principle , Software testing only needs to test the extended code , Because the original test code still works .

  2. It can improve the reusability of code

    The smaller the particle size , The more likely it is to be reused ; In object-oriented programming , According to the atom and abstract programming can improve the reusability of the code .

  3. It can improve the maintainability of software

    Software that follows the principle of opening and closing , It has high stability and continuity , So it's easy to expand and maintain .

How to realize the principle of opening and closing

Can pass “ Abstract constraints 、 Packaging changes ” To realize the principle of opening and closing , That is to define a relatively stable abstraction layer for software entities through interfaces or abstract classes , And encapsulate the same variables in the same concrete implementation class .

Because abstraction is flexible , Wide adaptability , As long as the abstract is reasonable , Can basically maintain the stability of the software architecture . And the changeable details in software can be extended by implementation classes derived from abstraction , When the software needs to change , You just need to re derive an implementation class according to the requirements to extend it .

Let's say Windows As an example, it introduces the application of opening and closing principle .

such as :Windows Desktop theme design

analysis :Windows The theme is desktop background pictures 、 The combination of window color and sound . Users can change their desktop themes according to their preferences , You can also download new themes from the Internet . These themes have common characteristics , You can define an abstract class for it (Abstract Subject), And every specific theme (Specific Subject) Is its subclass . The user form can select or add new themes as needed , Without modifying the original code , So it meets the opening and closing principle .
Java Technical debt

Richter's principle of substitution

The definition of Leeb's substitution principle

Richter's principle of substitution (Liskov Substitution Principle,LSP) By riskov of the computer science laboratory at MIT (Liskov) The lady is 1987 Year of “ The summit of object oriented technology ”(OOPSLA) An article published last week 《 Data abstraction and hierarchy 》(Data Abstraction and Hierarchy) What I mentioned in , She proposed : Inheritance must ensure that the properties owned by the superclass are still valid in the subclass (Inheritance should ensure that any property proved about supertype objects also holds for subtype objects).

The principle of Richter's substitution mainly expounds some principles of inheritance , That is, when inheritance should be used , When inheritance should not be used , And the principles behind it . Richter's substitution is the basis of inheritance reuse , It reflects the relationship between base class and subclass , It is a supplement to the principle of opening and closing , It's a specification of the concrete steps to achieve abstraction .

The role of the Richter principle

The main functions of the Riemannian substitution principle are as follows .

  1. Richter's replacement principle is one of the important ways to realize the opening and closing principle .
  2. It overcomes the disadvantage of poor reusability caused by overriding the parent class in inheritance .
  3. It's the guarantee of correct action . That is, the extension of class will not introduce new errors to the existing system , Reduces the possibility of code errors .
  4. Enhance the robustness of the program , At the same time, it can achieve very good compatibility when changing , Improve the maintainability of the program 、 Extensibility , Reduce the risk of requirements changes .

How to realize the principle of Leeb's substitution

Generally speaking, the principle of Leeb's substitution is : A subclass can extend the functionality of a parent class , But you cannot change the original functionality of the parent class . in other words : When a subclass inherits a parent class , In addition to adding new methods to complete the new functions , Try not to override the methods of the parent class .

According to the above understanding , The definition of Richter's substitution principle can be summarized as follows :

  • Subclasses can implement the abstract methods of the parent class , But you cannot override non-abstract methods of a parent class
  • Subclasses can add their own unique methods
  • When a method of a subclass overloads a method of a parent class , Method preconditions ( The input parameters of the method ) It's more relaxed than the parent class's method
  • When a method of a subclass implements a method of a parent class ( rewrite / Overloading or implementing abstract methods ), The postcondition of the method ( The output of the method / Return value ) Be more strict or equal than the methods of the parent class

It's easy to write by rewriting the methods of the parent class , But the reusability of the whole inheritance system is poor , Especially when polymorphism is frequently used , The probability of a program running wrong is very high .

If the procedure goes against the Richter principle , Then the object of the inherited class will run incorrectly where the base class appears . At this time, the correction method is : Cancel the original inheritance relationship , Redesign the relationship between them .

An example of the Richter's principle of substitution , The most famous is “ A square is not a rectangle ”. Of course , There are many similar examples in life , for example , penguin 、 Ostriches and kiwis are divided biologically , They belong to birds ; But from the perspective of class inheritance , Because they can't inherit “ bird ” The ability to fly , So they can't be defined as “ bird ” Subclasses of . Again , because “ Balloon fish ” Unable to swim , So it can't be defined as “ fish ” Subclasses of ;“ Toy gun ” Can't blow up the enemy , So it can't be defined as “ cannon ” And so on .

Let's say “ Kiwi is not a bird ” For example, to illustrate the principle of Riemannian substitution .

such as : The principle of Richter's substitution is “ Kiwi is not a bird ” Application in the example .

analysis : Birds usually fly , For example, the flying speed of swallows is about per hour 120 km . But Kiwi birds in New Zealand can't fly because their wings have degenerated . If you want to design an example , Calculate the flight of these two birds 300 Kilometers of time . obviously , Take swallow to test this code , Results the correct , Can calculate the time needed ; But take the kiwi to test , The result will happen “ Abnormal division by zero ” or “ infinity ”, Clearly not meeting expectations .

Java Technical debt

package principle;
public class LSPtest {

public static void main(String[] args) {

Bird bird1 = new Swallow();
Bird bird2 = new BrownKiwi();
bird1.setSpeed(120);
bird2.setSpeed(120);
System.out.println(" If you fly 300 km :");
try {

System.out.println(" The swallow will fly " + bird1.getFlyTime(300) + " Hours .");
System.out.println(" Kiwi will fly " + bird2.getFlyTime(300) + " Hours .");
} catch (Exception err) {

System.out.println(" Something went wrong !");
}
}
}
// birds 
class Bird {

double flySpeed;
public void setSpeed(double speed) {

flySpeed = speed;
}
public double getFlyTime(double distance) {

return (distance / flySpeed);
}
}
// Swallows 
class Swallow extends Bird {

}
// Kiwi birds 
class BrownKiwi extends Bird {

public void setSpeed(double speed) {

flySpeed = 0;
}
}

Java Technical debt

The reason why the program runs wrong is : Kiwi birds rewrite the setSpeed(double speed) Method , This goes against the principle of Riemannian substitution . The right thing to do is : Cancel the original inheritance relationship of Kiwi , A more general parent class that defines birds and kiwis , Like animals , They all have the ability to run . Although the speed of kiwi is 0, But running speed is not 0, You can calculate the run 300 Kilometers of time .

Java Technical debt

The principle of Dependence Inversion

Definition of the principle of dependency inversion

The principle of Dependence Inversion (Dependence Inversion Principle,DIP) yes Object Mentor Robert, President of the company · Martin (Robert C.Martin) On 1996 In C++ Report Articles published on .

The original definition of dependency inversion principle is : High level modules should not rely on low level modules , Both should rely on their abstractions ; Abstraction should not depend on details , Details should depend on abstraction (High level modules shouldnot depend upon low level modules.Both should depend upon abstractions.Abstractions should not depend upon details. Details should depend upon abstractions).

The central idea is this : Interface oriented programming , Don't program for implementation .

The principle of dependence inversion is one of the important ways to realize the principle of opening and closing , It reduces the coupling between the client and the implementation module .

Because in software design , The details are variable , The abstraction layer is relatively stable , So the architecture based on abstraction is much more stable than the architecture based on details . The abstraction here refers to the interface or abstract class , The details refer to the specific implementation class .

The purpose of using interfaces or abstract classes is to make specifications and contracts , Without any specific operation , Give their implementation classes the task of showing details to complete .

Rely on the function of the principle of inversion

The main functions of dependency inversion principle are as follows .

  • Dependency inversion principle can reduce the coupling between classes .
  • Depending on the inversion principle can improve the stability of the system .
  • Relying on the inversion principle can reduce the risk of parallel development .
  • Relying on the inversion principle can improve the readability and maintainability of the code .

Depending on the realization of the inversion principle

The purpose of dependency inversion principle is to reduce the coupling between classes through interface oriented programming , So we only need to follow the following in the actual programming 4 spot , You can meet this rule in the project .

  1. Each class tries to provide an interface or abstract class , Or both .
  2. The declaration type of variable should be interface or abstract class .
  3. No class should be derived from a concrete class .
  4. When using inheritance, try to follow the principle of leech substitution .

Let's say “ Customer shopping procedure ” As an example to illustrate the application of dependency inversion principle .

such as : The principle of Dependence Inversion lies in “ Customer shopping procedure ” Application in .

analysis : This procedure reflects “ Customers ” And “ Stores ” The relationship between . There are... In the store category sell() Method , Customer class through this method to shop the following code defines customer class through Shaoguan online store ShaoguanShop shopping :

class Customer {

public void shopping(ShaoguanShop shop) {

// shopping 
System.out.println(shop.sell());
}
}

however , There are disadvantages to this design , If the customer wants to go from another store ( Such as Wuyuan online store WuyuanShop) shopping , The customer's code should be modified as follows :

class Customer {

public void shopping(WuyuanShop shop) {

// shopping 
System.out.println(shop.sell());
}
}

Every time a customer changes a store , You have to change the code once , This obviously violates the opening and closing principle . The reason for the above shortcomings is : Customer class design is bound to specific store class , This goes against the principle of dependence inversion . The solution is : Definition “ Wuyuan online store ” and “ Shaoguan online shop ” Common interface Shop, The customer class is programmed for this interface , The code is modified as follows :

class Customer {

public void shopping(Shop shop) {

// shopping 
System.out.println(shop.sell());
}
}

such , No matter what kind of customers Customer What shops to visit , Or add new stores , No need to change the original code , The class diagram is as shown in the figure .

!Java Technical debt (https://img-blog.csdnimg.cn/img_convert/7da37ecf4635859ae6accaaf950c4128.gif)

The program code is as follows :

package principle;
public class DIPtest {

public static void main(String[] args) {

Customer wang = new Customer();
System.out.println(" Customers buy the following products :");
wang.shopping(new ShaoguanShop());
wang.shopping(new WuyuanShop());
}
}
// The store 
interface Shop {

public String sell(); // sell 
}
// Shaoguan online shop 
class ShaoguanShop implements Shop {

public String sell() {

return " Shaoguan local specialty : Xianggu mushroom 、 Black fungus ……";
}
}
// Wuyuan online store 
class WuyuanShop implements Shop {

public String sell() {

return " Wuyuan local specialty : Green tea 、 Fish in lees ……";
}
}
// customer 
class Customer {

public void shopping(Shop shop) {

// shopping 
System.out.println(shop.sell());
}
}

The program runs as follows :

 Customers buy the following products :
Shaoguan local specialty : Xianggu mushroom 、 Black fungus ……
Wuyuan local specialty : Green tea 、 Fish in lees ……

Principle of single responsibility

Definition of the principle of single responsibility

Principle of single responsibility (Single Responsibility Principle,SRP) Also known as single function principle , By Robert ·C. Martin (Robert C. Martin) On 《 Agile software development : principle 、 Patterns and practices 》 In a book . The duty here is to refer to the reason for the class change , The single responsibility principle states that a class should have only one reason for its change , Otherwise the class should be split (There should never be more than one reason for a class to change).

The principle states that the object should not bear too much responsibility , If an object takes on too many responsibilities , There are at least two disadvantages :

  1. A change in one responsibility may weaken or inhibit the ability of this class to implement other responsibilities ;
  2. When the client needs a certain responsibility of the object , I have to include all the other responsibilities I don't need , This will result in redundant code or code waste .

Advantages of the principle of single responsibility

The core of the single responsibility principle is to control the granularity of classes 、 Decouple objects 、 Improve its cohesion . If we follow the principle of single responsibility, we will have the following advantages .

  • Reduce class complexity . A class is responsible for only one responsibility , The logic is certainly much simpler than taking on multiple responsibilities .
  • Improve the readability of the class . Complexity reduction , Naturally its readability will improve .
  • Improve the maintainability of the system . Readability improvement , That's easier to maintain .
  • Risk reduction due to change . Change is inevitable , If the principle of single responsibility is followed well , When modifying a function , Can significantly reduce the impact on other functions .

How to realize the principle of single responsibility

The principle of single responsibility is the simplest but most difficult principle to apply , The designer needs to discover the different responsibilities of the class and separate them , Then encapsulate it into different classes or modules . The multiple responsibilities of discovery class require designers to have strong analysis and design ability and relevant reconstruction experience . The following takes the university student work management procedure as an example to introduce the application of the single responsibility principle .

such as : University student work management procedure .

analysis : College student work mainly includes two aspects: student life guidance and student academic guidance , Among them, life counseling mainly includes class committee construction 、 Attendance statistics 、 Counseling 、 A call for expenses 、 Class management, etc , Academic guidance mainly includes professional guidance 、 Study coaching 、 Scientific research guidance 、 Study and summarize . It's obviously unreasonable to leave these jobs to a teacher , Do it right Law is life guidance is in the charge of Counselors , Academic guidance is the responsibility of the academic tutor , The class diagram is as shown in the figure .

Java Technical debt

Be careful : Single responsibility also applies to methods . A method should do one thing as well as possible . If a method deals with too many things , It's going to get very coarse , Not conducive to reuse .

Interface isolation principle

Definition of interface isolation principle

Interface isolation principle (Interface Segregation Principle,ISP) Programmers are required to try their best to split the bloated interface into smaller and more specific interfaces , Let the interface contain only methods of interest to the customer .

2002 Robert ·C. Martin to “ Interface isolation principle ” Is defined as : The client should not be forced to rely on methods it does not use (Clients should not be forced to depend on methods they do not use). There is another definition of this principle : The dependency of one class on another should be based on the smallest interface (The dependency of one class to another one should depend on the smallest possible interface).

The meaning of the above two definitions is : To create the specialized interfaces they need for each class , Instead of trying to build a very large interface for all classes that depend on it to call .

The principle of interface isolation and single responsibility are both to improve the cohesion of classes 、 Reduce the coupling between them , It embodies the idea of encapsulation , But the two are different :

  • The principle of single responsibility focuses on responsibility , The principle of interface isolation focuses on the isolation of interface dependence .
  • The principle of single responsibility is mainly constraint , It aims at the implementation and details in the program ; The interface isolation principle mainly constrains the interface , Mainly for the construction of abstraction and program framework .

The advantages of the interface isolation principle

The principle of interface isolation is to constrain interfaces 、 Reduce the class's dependency on the interface , Follow the interface isolation principle as follows 5 advantage .

  1. Decompose the bulky interface into several interfaces with small granularity , Can prevent the spread of external changes , Improve the flexibility and maintainability of the system .
  2. Interface isolation improves the cohesion of the system , Reduced external interaction , It reduces the coupling of the system .
  3. If the granularity of an interface is well defined , It can guarantee the stability of the system ; however , If the definition is too small , It will cause too many interfaces , Complicate the design ; If the definition is too big , Less flexibility , Can't provide custom services , Bring unexpected risks to the whole project .
  4. Using multiple specialized interfaces can also reflect the level of objects , Because it can be inherited through the interface , Implement the definition of the total interface .
  5. It can reduce code redundancy in project engineering . Many different methods are usually placed in large interfaces , When implementing this interface , Forced to design redundant code .

How to implement the principle of interface isolation

In the specific application of interface isolation principle , It should be measured according to the following rules .

  • The interface should be as small as possible , But to a limited extent . An interface serves only a sub module or business logic .
  • Customize services for interface dependent classes . Provide only the methods the caller needs , Shield unwanted methods .
  • Understand the environment , Refuse to follow blindly . Each project or product has selected environmental factors , The environment is different , The standard of interface splitting is different. We need to have a deep understanding of business logic .
  • Improve cohesion , Reduce external interaction . Make the interface do the most things in the least way .

Next, take the student achievement management program as an example to introduce the application of interface isolation principle .

such as : Student achievement management procedure .

analysis : The student achievement management procedure generally includes inserting achievement 、 Delete grades 、 Revise grades 、 Calculate the total score 、 Calculate the average score 、 Print grade information 、 Query performance information and other functions , If you put all these functions in one interface, it's obviously not reasonable , The correct way is to put them in the input module 、 Statistics module and printing module 3 Of the modules , The class diagram is as shown in the figure .

Java Technical debt

The program code is as follows :

package principle;
public class ISPtest {

public static void main(String[] args) {

InputModule input = StuScoreList.getInputModule();
CountModule count = StuScoreList.getCountModule();
PrintModule print = StuScoreList.getPrintModule();
input.insert();
count.countTotalScore();
print.printStuInfo();
//print.delete();
}
}
// Input module interface 
interface InputModule {

void insert();
void delete();
void modify();
}
// Statistics module interface 
interface CountModule {

void countTotalScore();
void countAverage();
}
// Print module interface 
interface PrintModule {

void printStuInfo();
void queryStuInfo();
}
// Implementation class 
class StuScoreList implements InputModule, CountModule, PrintModule {

private StuScoreList() {

}
public static InputModule getInputModule() {

return (InputModule) new StuScoreList();
}
public static CountModule getCountModule() {

return (CountModule) new StuScoreList();
}
public static PrintModule getPrintModule() {

return (PrintModule) new StuScoreList();
}
public void insert() {

System.out.println(" Input module insert() Method is called !");
}
public void delete() {

System.out.println(" Input module delete() Method is called !");
}
public void modify() {

System.out.println(" Input module modify() Method is called !");
}
public void countTotalScore() {

System.out.println(" Statistics module countTotalScore() Method is called !");
}
public void countAverage() {

System.out.println(" Statistics module countAverage() Method is called !");
}
public void printStuInfo() {

System.out.println(" Printing module printStuInfo() Method is called !");
}
public void queryStuInfo() {

System.out.println(" Printing module queryStuInfo() Method is called !");
}
}

The program runs as follows :

 Input module insert() Method is called !
Statistics module countTotalScore() Method is called !
Printing module printStuInfo() Method is called !

Synthetic multiplexing principle

Definition of the principle of composite reuse

Synthetic multiplexing principle (Composite Reuse Principle,CRP) It's also called combination / Principle of aggregation and reuse (Composition/Aggregate Reuse Principle,CARP). It requires that when software is reused , Try to use association relationships such as composition or aggregation to achieve , Second, consider using inheritance relationship to achieve .

If you want to use inheritance , Then we must strictly follow the principle of Richter's replacement . The principle of composite reuse and the principle of Riemannian substitution complement each other , Both are the specific implementation norms of the opening and closing principles .

Importance of composite Reuse Principle

In general, class reuse is divided into inheritance reuse and composition reuse , Although inheritance reuse is simple and easy to implement , But it also has the following disadvantages .

  1. Inheritance reuse destroys class encapsulation . Because inheritance exposes the implementation details of the parent class to the child class , The parent class is transparent to the child class , So this reuse is also called “ White box ” Reuse .
  2. The coupling degree between subclass and parent is high . Any change in the implementation of the parent class will result in a change in the implementation of the child class , This is not conducive to class expansion and maintenance .
  3. It limits the flexibility of reuse . The implementation inherited from the parent class is static , Defined at compile time , So it's impossible to change at run time .

When combined or aggregated multiplexing is used , You can incorporate existing objects into new objects , Make it part of a new object , The new object can call the function of the existing object , It has the following advantages .

  1. It maintains class encapsulation . Because the internal details of the component object are invisible to the new object , So this reuse is also called “ black box ” Reuse .
  2. The coupling between new and old classes is low . This reuse requires less dependency , The only way a new object can access a component object is through its interface .
  3. High flexibility of reuse . This reuse can be done dynamically at run time , New objects can dynamically reference objects of the same type as component objects .

How to realize the principle of composite reuse

The principle of composite reuse is to integrate existing objects into new objects , Implemented as a member object of a new object , The new object can call the function of the existing object , To achieve reuse .

Next, take the automobile classification management program as an example to introduce the application of the synthesis Reuse Principle .

such as : Car classification management procedure .

analysis : Press the car “ Power source ” It can be divided into gasoline vehicles 、 Electric cars, etc ; Press “ Color ” It can be divided into white cars 、 Black car and red car etc . If you consider both categories , There are many combinations . The figure shows the class diagram of automobile classification realized by inheritance relationship .

Java Technical debt

As can be seen from the above figure, the implementation with inheritance relationship will generate many subclasses , And add new “ Power source ” Or add a new “ Color ” We need to change the source code , This goes against the principle of opening and closing , Obviously not desirable . But if we use the combination relationship implementation, we can solve the above problems well , The class diagram is as shown in the figure .

Java Technical debt

Dimitar's law

The definition of Dimiter's law

Dimitar's law (Law of Demeter,LoD) Also called the principle of least knowledge (Least Knowledge Principle,LKP), Produced in 1987 Northeastern University of the United States (Northeastern University) One of them is called Dimitar (Demeter) Research projects of , By Ian · Netherlands (Ian Holland) Put forward , By UML One of the founders, Butch (Booch) Universal , Later because in the classics 《 The way of programmer training 》(The Pragmatic Programmer) Mentioned and well known .

The definition of Dimiter's law is : Just talk to your direct friends , Not with “ A stranger ” speak (Talk only to your immediate friends and not to strangers). Its meaning is : If two software entities do not need to communicate directly , Then there should be no direct mutual calls , The call can be forwarded through a third party . The goal is to reduce the coupling between classes , Improve the relative independence of modules .

In Dimitar's law “ friend ” Refer to : The current object itself 、 Member object of current object 、 The object created by the current object 、 Method parameters of current object, etc , These objects are associated with the current object 、 Aggregate or combine relationships , Methods that can directly access these objects .

The advantages of Dimiter's law

Dimiter's law requires that the width and depth of communication between software entities be limited , There are two advantages of using Dimiter's law correctly .

  1. Reduce the coupling between classes , Improve the relative independence of the module .
  2. Due to the reduction of affinity , Thus, the reusability of the class and the expansibility of the system are improved .

however , Overuse of Dimiter's law will result in a large number of intermediary classes in the system , Thus increasing the complexity of the system , Reduce the communication efficiency between modules . therefore , In adopting Dimiter's law, we need to weigh repeatedly , Ensure high cohesion and low coupling at the same time , Make sure the structure of the system is clear .

The realization of Dimiter's law

It can be seen from the definition and characteristics of Dimiter's law , It emphasizes the following two points :

  1. From the perspective of the dependent , Rely only on what should be relied on .
  2. From the perspective of the dependent , Expose only the methods that should be exposed .

therefore , Pay attention to the following when using Dimitar's law 6 spot .

  1. In the division of classes , You should create weakly coupled classes . The weaker the coupling between classes , The more beneficial it is to achieve the goal of reusability .
  2. On the structure design of class , Minimize access to class members .
  3. On the design of class , Make it a priority to set a class to an immutable class .
  4. On references to other classes , Minimize the number of references to other objects .
  5. Don't expose property members of the class , The corresponding accessor should be provided (set and get Method ).
  6. Use serialization with caution (Serializable) function .

such as : Examples of the relationship between stars and agents .

analysis : The stars are devoted to art , So many daily affairs are handled by brokers , Such as meeting with fans , Business negotiations with media companies are weak . The agent here is a friend of the star , And fans and media companies are strangers , So it's good to use Dimitar's law , The class diagram is as shown in the figure .

Java Technical debt

The program code is as follows :

package principle;
public class LoDtest {

public static void main(String[] args) {

Agent agent = new Agent();
agent.setStar(new Star(" Lin Xinru "));
agent.setFans(new Fans(" Fan Han Cheng "));
agent.setCompany(new Company(" China Media Co., Ltd "));
agent.meeting();
agent.business();
}
}
// agent 
class Agent {

private Star myStar;
private Fans myFans;
private Company myCompany;
public void setStar(Star myStar) {

this.myStar = myStar;
}
public void setFans(Fans myFans) {

this.myFans = myFans;
}
public void setCompany(Company myCompany) {

this.myCompany = myCompany;
}
public void meeting() {

System.out.println(myFans.getName() + " With stars " + myStar.getName() + " To meet the .");
}
public void business() {

System.out.println(myCompany.getName() + " With stars " + myStar.getName() + " Business negotiation .");
}
}
// star 
class Star {

private String name;
Star(String name) {

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

return name;
}
}
// fans 
class Fans {

private String name;
Fans(String name) {

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

return name;
}
}
// Media company 
class Company {

private String name;
Company(String name) {

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

return name;
}
}

The program runs as follows :

 Fan Han Cheng met with star Lin Xinru .
China Media Co., Ltd. negotiated business with star Lin Xinru .

The author of this article :Java Technical debt
Link to the original text :https://www.cuizb.top/myblog/article/1655736095
Copyright notice : All articles in this blog except special statement , All adopt CC BY 3.0 CN License by agreement . For reprint, please sign the author and indicate the source of the article .

copyright:author[Java technology debt],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/202206240208283134.html