Design pattern principles of the Di-mitt law

Source: Internet
Author: User

The shorthand for the Dimitri rule is LoD, and the one in the middle is lowercase. Dimitri Law is also called to do the least knowledge principle (Least knowledge Principle, abbreviation LKP) said is a thing, an object should have the least understanding of other objects, a class on its own need to coupling or call class should know the least, you class inside is how complex, It doesn't matter how the tangle is with me, that's your class inside thing, I know you provide so many public methods, I call this; the Dimitri rule contains the following four meanings:

Communicate with friends only. Dimitri also has an English explanation is called "only speak to your immedate friends", communicates only with the direct friend, what is called the direct friend? Each object is bound to have a coupling relationship with other objects, and the coupling between the two objects becomes a friend, a relationship that has many such things as composition, aggregation, dependency, and so on. Let's just say an example of how to communicate with friends. said that there is such a story, the teacher wanted to let the sports Committee to confirm that the whole class of girls to do not, he said to him: "You go to the class of girls clear." "The sports committee did not hear clearly, or was at that time the brain is recalling something, asked:" Pro Which? "The Teacher ¥# ... ¥%. Let's see how this joke is implemented using a program, first look at the class diagram:

The source program for Teacher.java is as follows:

 PackageCom.cbf4life.common;Importjava.util.ArrayList;Importjava.util.List;/*** I ' m glad to share my knowledge and you all.* teacher class*/ Public classTeacher {//the teacher issued an order to the students to clear the girls Public voidCommond (Groupleader groupleader) {List<Girl> Listgirls =NewArrayList ();//Initializing Girls  for(inti=0;i<20;i++) {Listgirls.add (NewGirl ()); } //tell the Sports committee to start carrying out inventory tasks .Groupleader.countgirls (Listgirls);}}

Teacher has a method, issued orders to the Sports Committee, to check the number of girls. The following is the Sports Committee Groupleader.java source program:

 package   Com.cbf4life.common;  import   java.util.List;  /**  *   @author   Cbf4life [email protected]* I ' m glad to share my knowledge with you all.* Sports commissioner, this is too difficult to translate It's all Chinese characters.  */ public  class   Groupleader { //  There are women's jobs.  public  void  Countgirls (List<girl> Listgirls) {System. Out.println ( "Number of girls:" +listgirls.size ()); }}

Here is Girl.java, declaring a class without any code:

 Package Com.cbf4life.common; /**  @author  cbf4life [email protected]* I ' m glad to share my knowledge with you all.* schoolgirl * /  Public class Girl {}

Let's look at this business call class Client:

 PackageCom.cbf4life.common;/*** @authorcbf4life [email protected]* I ' m glad to share my knowledge with you all.* we use the client to depict this scene*/ Public classClient { Public Static voidMain (string[] args) {Teacher Teacher=NewTeacher ();//The teacher issued an orderTeacher.commond (NewGroupleader ()); }}

The results of the operation are as follows:

Number of girls: 20

We look back to see what the problem of this program, first of all, Teacher has a few friends, just a groupleader class, this is a friend class, friend class is how to define it? The class that appears in the member variable, the input and output parameters of the method is called the member friend class, the Dimitri rule says is a class only communicates with the friend class, but Commond method we and Girl class has the communication, declares a list dynamic array, namely with a strange class Girl has the communication, this bad, Let's change it again, class diagram or unchanged, first modify the Groupleader class, see the Source:

 PackageCom.cbf4life.common2;Importjava.util.ArrayList;Importjava.util.List;/*** @authorcbf4life [email protected]* I ' m glad to share my knowledge with you all.* Sports Committee, this is too difficult to translate is a Chinese characteristic vocabulary*/ Public classGroupleader {//have a job of checking out girls. Public voidCountgirls () {List<Girl> Listgirls =NewArraylist<girl>(); //Initializing Girls  for(inti=0;i<20;i++) {Listgirls.add (NewGirl ()); } System. Out.println ("Number of Girls is:" +listgirls.size ()); }}

Here is the Teacher.java program:

 Package Com.cbf4life.common2; /** * * I ' m glad to share my knowledge with you all.* teacher class */  Public class Teacher {// the teacher issued an order to the students, clear the girl publicvoid// tell the Sports committee to start carrying out inventory tasks . groupleader.countgirls ();}}

The program made a simple modification, that is, the Teacher in the list of initialization (this is a business sense, the generation of all the people in the class) moved to the Groupleader Countgrils method, avoid the Teacher class to unfamiliar Girl access, reduce The coupling between systems. Remember, a class only communicates with friends, does not communicate with unfamiliar classes, do not appear geta (). GETB (). GetC (). GETD () This situation (in the extreme case of allowing such access: the return type after each dot number is the same), and of course, the JDK API Provide class communication, otherwise you want to leave the compiler to exist!

There is also a distance between friends. There is a distance between people, too far is not a friend, too close to the whole body uncomfortable, and the relationship between the same, even if the friend class can not talk, omniscient. Everyone in the project should have encountered such a requirement: Call a class, then must first execute the first method, then the second method, depending on the return of the results to see if we can call the third method, or the fourth method, and so on, we use the class diagram to represent:

Very simple class diagram, to achieve the software installation process of the first step to do what, the second step to do what, the third step to do what such a process, we look at three classes of source code, first look at the Wizard Source:

 PackageCom.cbf4life.common3;ImportJava.util.Random;/*** @authorcbf4life [email protected]* I ' m glad to share my knowledge with you all.* follow the steps of the business logic class*/ Public classWizard {PrivateRandom Rand =NewRandom (System. Currenttimemillis ()); Public intFirst () {System. OUT.PRINTLN ("Execute the first method ..."); returnRand.nextint (100); }//Step Two Public intsecond () {System. OUT.PRINTLN ("Execute a second method ..."); returnRand.nextint (100); }//a third method Public intthird () {System. OUT.PRINTLN ("Perform a third method ..."); returnRand.nextint (100); }}

Three step methods are defined, each with relevant business logic to complete the specified task, and we use a random function instead of the return value of the business execution. Then look at the software installation process Installsoftware Source:

 PackageCom.cbf4life.common3;/*** @authorcbf4life [email protected]* I ' m glad to share my knowledge with you all.* business Assembly class, responsible for invoking each step*/ Public classInstallsoftware { Public voidInstallwizard (Wizard Wizard) {intFirst =Wizard.first ();//Depending on the results returned by first, see if you need to perform second if(first>50){ intSecond =Wizard.second ();if(second>50){ intThird =Wizard.third ();if(Third >50{Wizard.first (); }}}}}

Where Installwizard is a wizard-like installation step, we see how the scene is called:

 package   Com.cbf4life.common3;  /**  *   @author   Cbf4life [email protected]* I ' m glad to share my knowledge with your all.* business scenario  Span style= "color: #008000;" >*/ public  class   Client { public  static  void   main (string[] args) {installsoftware invoker  = new   Installsoftware (); Invoker.installwizard ( new   Wizard ()); }}

This program is very simple, running results and random numbers related, I will not paste it up. Let's think about what's wrong with this program? The Wizard class exposes too many methods to the Installsoftware class, so the coupling relationship is very tight, I want to change the return value of a method, it is an int, now change to a Boolean, you need to modify the other classes, such a coupling is extremely inappropriate, Dmitri Special law requires the class "stingy" point, try not to disclose too many public methods and non-static variables, as far as possible, use private,package-private, protected and other access rights. Let's change the class diagram:

Let's take a look at the program changes and see the Wizard program first:

 PackageCom.cbf4life.common4;ImportJava.util.Random;/*** @authorcbf4life [email protected]* I ' m glad to share my knowledge with you all.* follow the steps of the business logic class*/ Public classWizard {PrivateRandom Rand =NewRandom (System. Currenttimemillis ());//The first stepPrivate intFirst () {System. OUT.PRINTLN ("Execute the first method ..."); returnRand.nextint (100); }//Step TwoPrivate intsecond () {System. OUT.PRINTLN ("Execute a second method ..."); returnRand.nextint (100); }//a third methodPrivate intthird () {System. OUT.PRINTLN ("Perform a third method ..."); returnRand.nextint (100); }//Software Installation Process Public voidInstallwizard () {intFirst = This. First ();//Depending on the results returned by first, see if you need to perform second if(first>50){ intSecond = This. second ();if(second>50){ intThird = This. third ();if(Third >50){  This. First ();} } } }
}

The three-step access is modified to private, and the Installewizad is moved by the wizard method, so that the wizard class only publishes a public method, the class of high-cohesion specific display. We'll see Installsoftware source code:

 package   Com.cbf4life.common4;  /**  *   @author   Cbf4life [email protected]* I ' m glad to share my knowledge with you all.* business Assembly class, responsible for invoking each Step  */ public  class   Installsoftware { public  Span style= "color: #0000ff;" >void   Installwizard (Wizard wizard) { //   No nonsense, call directly   Wizard.installwizard ();}}  

The Client class does not have any changes, it is not copied, so that our program to do a weak coupling, a class to publish more public properties or methods, the modification of the involved face is greater, that is, the risk of change is greater. Therefore, in order to maintain the distance between friends, you need to do is: reduce the public method, more use of private, package-private (this is the package type, the class, methods, variables without access rights, the default is the package type) protected and other access rights, reduce non- Static Public property, if the member variable or method can be added with the final keyword, do not let the outside to change it.

Is their own is their own. There are some methods in the project that can be put in this class, and there are no errors in other classes, how to measure? You can stick to the principle that if a method is placed in this class, without increasing the relationship between the classes, and not negatively affecting the class, it is placed in this class.

Use Serializable sparingly. To tell you the truth, this problem will be very rare, even if it appears, it will find the problem immediately. What's going on here? For example, if you use R M I to pass an object VO (Va Lu E object), this object must use the Serializable interface, which is to serialize your object and then network it. Suddenly one day, the client's VO object modifies the access rights of a property, changes from private to public, and if no response changes are made on the server, the serialization failure is reported. This should belong to the project management category, a class or interface client changed, and the service side has not changed, that is?!

The core concept of the Dimitri law is the decoupling between classes, weak coupling, only weak coupling, the class of the reuse rate can be improved, the result of its requirements is to produce a large number of relays or jump class, the class can only communicate with friends, friends less your business to run, more friends, you project management complex, You have to weigh each other when you use it.

Do not know if you have heard such a theory: "Any 2 strangers among the most only 6 people, that is, only 6 people can connect them together", the scientific name of this theory is called "Six Degrees Separation", applied to our project that I and I want to call the class between a maximum of 6 passes, hehe, It's going to be a fun time for everyone to see. In the actual project you jump two times to access a class estimate you will find a way, it is also reasonable, Dimitri Law requires us to decouple the class, but the decoupling is limited, unless it is the smallest symbol of the computer binary 0 and 1, that is fully decoupled, we in the actual project, Need to consider this law moderately, do not do the project for the application of the law, the law is only a reference, you jump out of this rule, no one will sentence you, the project will not fail, which requires you to consider how to measure the law. (Transferred from 24 design modes)

Design pattern principles of the Di-mitt law

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.