设计模式原则——迪米特法则原则

设计模式原则

设计模式示例代码库地址:

https://gitee.com/Jasonpupil/designPatterns

迪米特法则原则:

  • 意义在于降低类之间的耦合。由于每个对象尽量减少对于其他对象的了解,因此,很容易使得系统的功能模块功能独立,相互之间不存在(或很少有)依赖关系
  • 迪米特法则还有一个英文解释是:talk only to your immediate friends(只和直接的朋友交流)
  • 什么是朋友:每个对象基本上会与其他的对象有耦合关系,当两个对象之间耦合就会成为朋友关系
  • 什么是直接朋友:出现在成员变量局部变量全局变量方法的输入输出参数中的类就是直接的朋友

模式场景:学生成绩&排名

  • 迪米特法则替换前:教师管理班级里的学生,校长通过教师获取班里的学生来统计出班级的总分、平均分和班级人数
  • 迪米特法则替换后:教师管理班级里的学生,统计出班级的总分、平均分和班级人数由教师来做,校长只需要根据班级寻找老师获取相应的信息

迪米特法则替换前示例代码:

校长类:
/*** @Description: 校长* @Author: pupil* @Date: 2024/06/24 下午 1:13*/
public class Principal {private Teacher teacher = new Teacher("智盛", "3年1班");// 查询班级信息,总分数、学生人数、平均值public Map<String, Object> queryClazzInfo(String clazzId) {// 获取班级信息;学生总人数、总分、平均分int stuCount = clazzStudentCount();double totalScore = clazzTotalScore();double averageScore = clazzAverageScore();// 组装对象,实际业务开发会有对应的类Map<String, Object> mapObj = new HashMap<>();mapObj.put("班级", teacher.getClazz());mapObj.put("老师", teacher.getName());mapObj.put("学生人数", stuCount);mapObj.put("班级总分数", totalScore);mapObj.put("班级平均分", averageScore);return mapObj;}// 总分public double clazzTotalScore() {double totalScore = 0;for (Student stu : teacher.getStudents()) {totalScore += stu.getScore();}return totalScore;}// 平均分public double clazzAverageScore(){double totalScore = 0;for (Student stu : teacher.getStudents()) {totalScore += stu.getScore();}return totalScore / teacher.getStudents().size();}// 班级人数public int clazzStudentCount(){return teacher.getStudents().size();}}
老师类:
/*** @Description: 教师* @Author: pupil* @Date: 2024/06/24 下午 1:14*/
public class Teacher {private String name;    // 学生姓名private String clazz;   // 班级private static List<Student> students;  // 学生public Teacher() {}public Teacher(String name, String clazz) {this.name = name;this.clazz = clazz;}static {students = new ArrayList<>();students.add(new Student("王五", 10, 589));students.add(new Student("李四", 100, 256));students.add(new Student("小三", 23, 449));students.add(new Student("皮皮", 2, 665));students.add(new Student("蛋蛋", 15, 532));}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getClazz() {return clazz;}public void setClazz(String clazz) {this.clazz = clazz;}public static List<Student> getStudents() {return students;}public static void setStudents(List<Student> students) {Teacher.students = students;}
}
学生类:
/*** @Description: 学生* @Author: pupil* @Date: 2024/06/24 下午 1:14*/
public class Student {private String name;    // 学生姓名private int rank;       // 考试排名(总排名)private double score;   // 考试分数(总分)public Student() {}public Student(String name, int rank, double score) {this.name = name;this.rank = rank;this.score = score;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getRank() {return rank;}public void setRank(int rank) {this.rank = rank;}public double getScore() {return score;}public void setScore(double score) {this.score = score;}
}
测试类:
/*** @Description: 测试验证* @Author: pupil* @Date: 2024/06/24 下午 3:09*/
public class ApiTest {private Logger logger = LoggerFactory.getLogger(ApiTest.class);@Testpublic void test_Principal(){Principal principal = new Principal();Map<String, Object> map = principal.queryClazzInfo("3年1班");logger.info("查询结果:{}", JSON.toJSONString(map));}
}
结果:

在这里插入图片描述

迪米特法则替换后示例代码:

校长类:
/*** @Description: 校长* @Author: pupil* @Date: 2024/06/24 下午 1:13*/
public class Principal {private Teacher teacher = new Teacher("智盛", "3年1班");// 查询班级信息,总分数、学生人数、平均值public Map<String, Object> queryClazzInfo(String clazzId) {// 获取班级信息;学生总人数、总分、平均分int stuCount = teacher.clazzStudentCount();double totalScore = teacher.clazzTotalScore();double averageScore = teacher.clazzAverageScore();// 组装对象,实际业务开发会有对应的类Map<String, Object> mapObj = new HashMap<>();mapObj.put("班级", teacher.getClazz());mapObj.put("老师", teacher.getName());mapObj.put("学生人数", stuCount);mapObj.put("班级总分数", totalScore);mapObj.put("班级平均分", averageScore);return mapObj;}
}
老师类:
/*** @Description: 教师* @Author: pupil* @Date: 2024/06/24 下午 1:14*/
public class Teacher {private String name;    // 学生姓名private String clazz;   // 班级private static List<Student> students;  // 学生public Teacher() {}public Teacher(String name, String clazz) {this.name = name;this.clazz = clazz;}static {students = new ArrayList<>();students.add(new Student("王五", 10, 589));students.add(new Student("李四", 100, 256));students.add(new Student("小三", 23, 449));students.add(new Student("皮皮", 2, 665));students.add(new Student("蛋蛋", 15, 532));}// 总分public double clazzTotalScore() {double totalScore = 0;for (Student stu : getStudents()) {totalScore += stu.getScore();}return totalScore;}// 平均分public double clazzAverageScore(){double totalScore = 0;for (Student stu : getStudents()) {totalScore += stu.getScore();}return totalScore / getStudents().size();}// 班级人数public int clazzStudentCount(){return getStudents().size();}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getClazz() {return clazz;}public void setClazz(String clazz) {this.clazz = clazz;}public static List<Student> getStudents() {return students;}public static void setStudents(List<Student> students) {Teacher.students = students;}
}
学生类:
/*** @Description: 学生* @Author: pupil* @Date: 2024/06/24 下午 1:14*/
public class Student {private String name;    // 学生姓名private int rank;       // 考试排名(总排名)private double score;   // 考试分数(总分)public Student() {}public Student(String name, int rank, double score) {this.name = name;this.rank = rank;this.score = score;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getRank() {return rank;}public void setRank(int rank) {this.rank = rank;}public double getScore() {return score;}public void setScore(double score) {this.score = score;}
}
测试类:
/*** @Description: 测试验证* @Author: pupil* @Date: 2024/06/24 下午 3:09*/
public class ApiTest {private Logger logger = LoggerFactory.getLogger(ApiTest.class);@Testpublic void test_Principal(){Principal principal = new Principal();Map<String, Object> map = principal.queryClazzInfo("3年1班");logger.info("查询结果:{}", JSON.toJSONString(map));}
}
结果:

在这里插入图片描述

根据迪米特法则原则的示例类图:

在这里插入图片描述
校长类与教师类是聚合关系

教师类与学生类是聚合关系

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/34939.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[论文笔记]Mixture-of-Agents Enhances Large Language Model Capabilities

引言 今天带来一篇多智能体的论文笔记&#xff0c;Mixture-of-Agents Enhances Large Language Model Capabilities。 随着LLMs数量的增加&#xff0c;如何利用多个LLMs的集体专业知识是一个令人兴奋的开放方向。为了实现这个目标&#xff0c;作者提出了一种新的方法&#xf…

Erpnext安装

Erpnext安装 环境要求 Ubuntu 23.04 x86_64 Python 3.10.12 pip 23.0.1 node v18.16.0 npm 9.5.1 yarn 1.22.22 MariaDB 10.11.2 Redis 7.0.8 wkhtmltox 0.12.6.1 bench 5.22.6环境安装 Reids 安装 // 安装7.0.8 也可不指定版本 直接执行 sudo apt install redis-server s…

Spring Boot 3 搭建

1、jdk 17 2、spring boot 3.1.7 3、pom.xml <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xs…

在线客服源码系统全端通用 源码完全开源可以二次开发 带完整的安装代码包以及搭建教程

系统概述 在线客服源码系统采用了先进的技术架构&#xff0c;包括前端界面、后端服务、数据库等部分。前端界面采用了响应式设计&#xff0c;能够自适应不同的设备屏幕尺寸&#xff0c;为用户提供良好的使用体验。后端服务采用了高性能的服务器架构&#xff0c;确保系统的稳定…

【面向对象】复习(三)

this指针 本职&#xff1a;指针常量&#xff0c;指向当前对象 不能访问静态成员&#xff0c;因为静态成员属于类&#xff0c;this指针属于对象 不要返回局部变量的引用或指针 int f(){ int a1; return a;}//a是函数外的&#xff0c;函数结束不释放 A * f(A & a){return…

QT学习积累——在C++中,for循环中使用``与不使用``的区别和联系

目录 引出使用&与不使用&除法的一个坑 总结自定义信号和槽1.自定义信号2.自定义槽3.建立连接4.进行触发 自定义信号重载带参数的按钮触发信号触发信号拓展 lambda表达式返回值mutable修饰案例 引出 QT学习积累——在C中&#xff0c;for循环中使用&与不使用&的…

即时发布,市场担忧导致比特币和以太坊全线暴跌

来源:币界网 作者:636Marx 币界网新闻 – 2024 年 6 月 25 日– 数字货币市场形势急转直下&#xff0c;两种主力的数字货币比特币和以太坊的价格大幅下跌&#xff0c;给数字货币市场带来冲击。比特币再次触及$60,000美元关口&#xff0c;而以太坊反弹乏力&#xff0c;在 3,300…

PointCloudLib (多线程)快速双边滤波 C++版本

0.实现效果 原始点云 和滤波后的点云对比 1.算法原理 PCL(Point Cloud Library)快速双边滤波是一种高效的点云数据滤波方法,它基于传统双边滤波算法进行了改进,通过引入近似方法加速计算过程。以下是关于PCL快速双边滤波的详细回答: 1. 基本原理 空间滤波:在点云中,相…

详解 ClickHouse 的 MaterializeMySQL 引擎

注意与 ClickHouse 的 MySQL 表引擎区分开 一、概述 ClickHouse 20.8.2.3 版本新增加了 MaterializeMySQL 的 database 引擎&#xff0c;该 database 能映射到 MySQL 中的某个 database &#xff0c; 并自动在 ClickHouse 中创建对应的 ReplacingMergeTree。ClickHouse 服务做…

Verilog的逻辑系统及数据类型(一):四值逻辑系统

目录 1. Verilog采用的四值逻辑系统2.主要数据类型2.1 net&#xff08;线网&#xff09;2.2 寄存器类 &#xff08;register)2.3 Verilog中net和register声明语法2.3.1 net声明2.3.2 寄存器声明 2.4 选择正确的数据类型2.5 选择数据类型时常犯的错误2.5.1 信号类型确定方法总结…

【嵌入式DIY实例】-Nokia 5110显示BME280传感器数据

Nokia 5110显示BME280传感器数据 文章目录 Nokia 5110显示BME280传感器数据1、硬件准备与接线2、代码实现本文将介绍如何使用 ESP8266 NodeMCU 板(ESP12-E 模块)和 BME280 气压、温度和湿度传感器构建一个简单的本地气象站。 NodeMCU 从 BME280 传感器读取温度、湿度和压力值…

2024广东省职业技能大赛云计算赛项实战——集群部署GitLab Runner

集群部署GitLab Runner 前言 题目如下: 部署GitLab Runner 将GitLab Runner部署到gitlab-ci命名空间下&#xff0c;Release名称为gitlab-runner&#xff0c;为GitLab Runner创建持久化构建缓存目录/home/gitlab-runner/ci-build-cache以加速构建速度&#xff0c;并将其注册到…

【算法与数据结构】【字符串篇】【String的常见函数】

系列文章 本人系列文章-CSDN博客https://blog.csdn.net/handsomethefirst/article/details/138226266?spm1001.2014.3001.5502 1.string基本概念 string是C风格的字符串&#xff0c;而string本质上是一个类。 string和char * 区别&#xff1a; char * 是一个指针 string是一…

Linux操作系统:从入门到精通

前言 Linux操作系统是当今计算机世界中的重要一环。它不仅在服务器和企业级应用中广泛使用&#xff0c;同时也是许多开发者和技术爱好者的首选。本文将带你全面了解Linux操作系统的基础知识、常用命令及其在不同领域的应用。 一、Linux简介 1.1 什么是Linux&#xff1f; Li…

Java常用类2

StringBuffer和StringBuilder StringBuffer与StringBuilder类介绍 StringBuffer是String的对等类&#xff0c;提供了许多字符串功能。您可能知道&#xff0c;String表示长度固定、不可修改的字符序列。与之相对应&#xff0c;StringBuffer表示可增长、可写入的字符序列。Stri…

重写equals为什么要重写hashCode???

当你在Java中重写了equals()方法后&#xff0c;通常建议你也应该重写hashCode()方法。这是基于Java集合框架的设计原则&#xff0c;具体来说是基于Object类中的equals()和hashCode()方法之间的约定。以下是为什么需要这样做的一些关键原因&#xff1a; 一致性原则&#xff1a;…

[Redis]缓存常见问题解决(缓存穿透、击穿、雪崩一文解决!通俗易懂、代码实战!手把手教你解决缓存问题三兄弟!)

Redis常见问题解决 要求 只用一种缓存技术&#xff0c;从实验点中挑一些试验进行试验原理。 1.缓存原理 目标&#xff1a;理解缓存的基本原理和工作机制。 实验步骤&#xff1a; 阅读各缓存技术机制的文档和官方资料。实现一个简单的应用程序&#xff0c;模拟数据的读写和…

音视频入门基础:H.264专题(4)——NALU Header:forbidden_zero_bit、nal_ref_idc、nal_unit_type简介

音视频入门基础&#xff1a;H.264专题系列文章&#xff1a; 音视频入门基础&#xff1a;H.264专题&#xff08;1&#xff09;——H.264官方文档下载 音视频入门基础&#xff1a;H.264专题&#xff08;2&#xff09;——使用FFmpeg命令生成H.264裸流文件 音视频入门基础&…

试析C#编程语言的特点及功能

行步骤&#xff0c;而不必创建新方法。其声明方法是在实例化委托基础上&#xff0c;加一对花括号以代表执行范围&#xff0c;再加一个分号终止语句。 2.3.3 工作原理 C#编译器在“匿名”委托时会自动把执行代码转换成惟一命名类里的惟一命名函数。再对存储代码块的委托进行设…

【C语言】16 位的值,通过几种不同的方式将其拆分为高 8 位和低 8 位

当我们想要将一个16位的 Register_Value 拆分成高8位和低8位&#xff0c;并存储到 Send_Data_Uart5 数组中时&#xff0c;有几种常见的方法可以实现。让我们逐一优化和详细分析每种方法&#xff1a; 方法 1: 使用位移和位掩码&#xff08;常用方法&#xff09; Send_Data_Uar…