设计模式之迪米特法则

迪米特法则(Law of Demeter,简称LoD) 低耦合,一个对象应该对其他对象保持最少的了解(中介者模式就是这个的应用)

  • 核心思想: 类间解耦。
  • 通俗来讲: 一个类对自己依赖的类知道的越少越好。自从我们接触编程开始,就知道了软件编程的总的原则:低耦合,高内聚。无论是面向过程编程还是面向对象编程,只有使各个模块之间的耦合尽量的低,才能提高代码的复用率。低耦合的优点不言而喻,但是怎么样编程才能做到低耦合呢?那正是迪米特法则要去完成的。

错误示范:

public class Teacher {
    public void command(){
        //耦合了student类
        List<Student> students = new ArrayList<Student>();
        for(int i=0; i<20; i++){
            students.add(new Student());
        }
        
        //耦合了studentleader类
        StudentLeader leader = new StudentLeader();
        System.out.println("清点人数完毕,总共有:"+leader.counts(students)+"人");
        
    }
}

public class Student {

}

//班干部负责清点人数
public class StudentLeader {
    public int counts(List<Student> lists){
        return lists.size();
    }
}

public class Client{
    public static void main(String[] args){
        System.out.println("周末收假,学校领导命令老师去点名.....");
        Teacher teacher = new Teacher();
        teacher.command();
    }
}

 

 

正确示范:

public class LODTeacher {
    //仅仅耦合了LODStudentLeader类
    public void command(LODStudentLeader leader){
        System.out.println("清点人数完毕,总共有:"+leader.counts()+"人");
    }
}

public class LODStudentLeader {
    //仅仅耦合了student类
    private List<Student> students;
    
    public LODStudentLeader(List<Student> students){
        this.students = students;
    }
    public int counts(){
        return students.size();
    }
}

public class TaskTest {
    public static void main(String[] args) {
        System.out.println("周末收假,学校领导命令老师去点名.....");
        List<Student> students = new ArrayList<Student>();
        for(int i = 0; i < 20; i++ ){
              students.add(new Student());
        }
        LODTeacher teacher = new LODTeacher();
        teacher.command(new LODStudentLeader(students));
    }
}

 

    原文作者:设计模式
    原文地址: https://www.cnblogs.com/o-andy-o/p/10344277.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞