2.0 - Design Patterns seven principles of software architecture design - Demeter

Dimitris principle (Law of Demeter LoD) refers to an object to be kept to a minimum understanding of other objects, also known as the least known principle (Least Knowledge Principle, LKP), to minimize the coupling between a class and class. Dimitris principle the main emphasis and communicate with friends only, do not talk to strangers. Appears in the member variable, process input and output parameters can be called a member of the class friend class, now inside out method body does not belong to the class friends category.

Now to design a permissions system, Boss need to find out the number of courses to release the line. At this time, Boss to find TeamLeader to statistics, TeamLeader statistical results and then tell Boss. Next we look at the code:

/**
 * @author madongyu
 * @projectName design-pattern-ma
 * @description: 课程
 * @date 2019/6/1717:57
 */
public class Curriculum {

}
/**
 * @author madongyu
 * @projectName design-pattern-ma
 * @description: TODO
 * @date 2019/6/1816:21
 */
public class TeamLeader {
    public void checkNumberOfCourses(List<Curriculum> courseList){
        System.out.println("目前已发布的课程数量是:"+courseList.size());
    }
}
public class Boss {
    public void commandCheckNumber(TeamLeader teamLeader){
       //模拟 Boss 一页一页往下翻页,TeamLeader 实时统计
        List<Curriculum> courseList = new ArrayList<Curriculum>();
        for (int i= 0; i < 20 ;i ++){
            courseList.add(new Curriculum());
        }
        teamLeader.checkNumberOfCourses(courseList);
    }


    public static void main(String[] args) {
        Boss boss = new Boss();
        TeamLeader teamLeader = new TeamLeader();
        boss.commandCheckNumber(teamLeader);
    }
}

I write to you, in fact, have already been achieved function, the code looks okay. According to Dmitry principle, Boss just want a result, no direct communication with the Curriculum. The statistics TeamLeader need to reference the Curriculum object. Boss and Curriculum are not friends and from the following class diagram can be seen:

 

Let's reform the code:

TeamLeader categories:

public void checkNumberOfCourses(){
        List<Curriculum> courseList = new ArrayList<Curriculum>();
        for(int i = 0 ;i < 20;i++){
            courseList.add(new Curriculum());
        }
        System.out.println("目前已发布的课程数量是:"+courseList.size());
    }

Boss class

 public void commandCheckNumber(TeamLeader teamLeader){
        teamLeader.checkNumberOfCourses();
    }

Consider the following class diagram, Boss, and no relationship Curriculum

Guess you like

Origin blog.csdn.net/madongyu1259892936/article/details/93597224