ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
**迪米特法则**:不该知道的不要知道,一个类应该保持对其它对象最少的了解,降低耦合度 高内聚、低耦合:**简单理解为:是你的,就别给别人;不是你的,就别拿** 迪米特原则(LoD)也被称为最少知识原则(LKP),它强调一个对象应该对其他对象有尽可能少的了解。换句话说,一个类不应该直接与其他许多类产生耦合,而应该通过尽可能少的中介对象进行通信。 下面通过一个简单的 PHP 示例来说明迪米特原则: ~~~ class Teacher { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } class Course { private $name; private $teacher; public function __construct($name, $teacher) { $this->name = $name; $this->teacher = $teacher; } public function getName() { return $this->name; } public function getTeacherName() { return $this->teacher->getName(); // 违反迪米特原则,Course 类直接依赖于 Teacher 类的具体实现 } } class School { private $courses; public function __construct() { $this->courses = []; } public function addCourse($name, $teacherName) { $teacher = new Teacher($teacherName); $course = new Course($name, $teacher); $this->courses[] = $course; } public function printCourses() { foreach ($this->courses as $course) { echo "Course: " . $course->getName() . ", Teacher: " . $course->getTeacherName() . "\n"; } } } $school = new School(); $school->addCourse("Math", "John"); $school->addCourse("English", "Jane"); $school->printCourses(); ~~~ 在上面的示例中,我们有三个类 `Teacher`、`Course` 和 `School`。`Teacher` 类表示教师,`Course` 类表示课程,`School` 类表示学校。`Course` 类中的 `getTeacherName` 方法直接调用了 `Teacher` 类的 `getName` 方法,违反了迪米特原则。根据迪米特原则,`Course` 类不应该直接依赖于 `Teacher` 类的具体实现,而应该通过尽可能少的中介对象进行通信。 为了符合迪米特原则,我们可以将 `Course` 类中的 `getTeacherName` 方法修改如下: ~~~ public function getTeacherName() { return $this->teacherName; } ~~~ 这样,`Course` 类只返回教师的名字,而不直接调用 `Teacher` 类的方法。这样做的好处是减少了 `Course` 类对其他类的依赖,降低了耦合性,提高了代码的可维护性和灵活性。 总之,迪米特原则要求一个对象尽可能少地了解其他对象,通过尽可能少的中介对象进行通信。这样可以减少类之间的耦合度,增强代码的灵活性和可维护性。