星语课程网
耦合和内聚Java代码展示
来源:本站编辑
2023-11-21 16:50
46
# 通过 Java 程序来反映各种类型的耦合、内聚 - 耦合性是用来描述模块之间的独立程度。这里讲模块之间的耦合程度分为六个程度 R0-R5 (Ri >Rj, i > j)。分别是无耦合,数据耦合,标记耦合,控制耦合,共同耦合, 内容耦合。 ## 1. 无耦合 R0: 模块 X 与模块 Y 没有交互 ## 2. 数据耦合 R1: 模块 X 与模块 Y 之间有调用关系,传递的是
**简单的数据值**
,相当于高级语言的
值传递
。一个模块访问另一个模块时,彼此之间是通过简单数据参数 (不是控制参数、公共 数据结构或外部变量) 来交换输入、输出信息的。 代码模拟: ```java package metrics.coupling.data; import metrics.coupling.data.Person; public class Main { public static void main(String[] args) { Person person = new Person(1.8, 56); double height = person.getHeight(); double weight = person.getWeight(); double BMI = BMIUtils.getBMI(height, weight); System.out.println("BMI:" + BMI); } } package metrics.coupling.data; public class Person { private double height; private double weight; public Person(double height, double weight) { super(); this.height = height; this.weight = weight; } public Person() { super(); // TODO Auto-generated constructor stub } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } } package metrics.coupling.data; public class BMIUtils { public static double getBMI(double height, double weight) { return weight / (Math.pow(height, 2)); } } ``` ## 3. 标记耦合 R2: 模块 X 与模块 Y 之间传递的是数据结构(
复合数据类型
),一般是指传的是
改数据的地址
。 代码模拟: ```java package metrics.coupling.stamp; import metrics.coupling.stamp.BMIUtils; import metrics.coupling.stamp.Person; public class Main { public static void main(String[] args) { Person person = new Person(1.8, 56); double BMI = BMIUtils.getBMI(person); System.out.println("BMI:" + BMI); } } package metrics.coupling.stamp; public class Person { private double height; private double weight; public Person(double height, double weight) { super(); this.height = height; this.weight = weight; } public Person() { super(); // TODO Auto-generated constructor stub } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } } package metrics.coupling.stamp; public class BMIUtils { public static double getBMI(Person person) { return person.getWeight() / (Math.pow(person.getHeight(), 2)); } } ``` ## 4. 控制耦合 R3: 模块 X 将
参数
传递给模块 Y 用以
控制
模块 Y 的行为 代码模拟: ```java package metrics.coupling.control; public class Main { public static void main(String[] args) { Person person = new Person("man"); if ("man".equals(person.getSex())) { System.out.println("是一个男生"); } else if ("woman".equals(person.getSex())) { System.out.println("是一个女生"); } else { System.out.println("没准是泰国来的"); } } } package metrics.coupling.control; public class Person { private String sex; public Person() { super(); // TODO Auto-generated constructor stub } public Person(String sex) { super(); this.sex = sex; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } } ``` ## 5. 共同/公共 耦合 R4: 模块 X 与模块 Y 共享相同的
全局变量
。 代码模拟: ```java package metrics.coupling.common; public class Main { static StringBuffer mBuffer; public static void main(String[] args) { mBuffer = new StringBuffer("我是一个字符串 "); StringOP1.operate(mBuffer); I StringOP2.operate(mBuffer); System.out.println(mBuffer.toString()); } } package metrics.coupling.common; public class StringOP1 { public static void operate(StringBuffer mBuffer) { mBuffer.append("第一次修改;"); } } package metrics.coupling.common; public class StringOP2 { public static void operate(StringBuffer mBuffer) { mBuffer.append("第一次修改;"); } } ``` ## 6. 内容耦合 R5:
模块 X 直接修改或操作模块 Y 的数据
,或者直接转入模块 Y。 代码模拟: ```java package metrics.coupling.content; public class Main { static StringBuffer mBuffer; public static void main(String[] args) { mBuffer = new StringBuffer("我是一个字符串 "); StringOP1.operate(mBuffer); //StringOP2.operate(mBuffer); System.out.println(mBuffer.toString()); } } package metrics.coupling.content; public class StringOP1 { public static void operate(StringBuffer mBuffer) { mBuffer.append("第一次修改;"); StringOP2.operate(mBuffer); I } } package metrics.coupling.content; public class StringOP2 { public static void operate(StringBuffer mBuffer) { mBuffer.append("第一次修改;"); } } ``` # 内聚: 内聚是将为了完成相同的任务的范围的程度。分为功能内聚,顺序内聚,通信内聚,过 程内聚,时间内聚,耦合内聚。 ## . 功能内聚: 模块只执行一个单一定义良好的功能。 ```java import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; /** * 比较两张图片的相似度 * * @author Guihua * */ public class BMPLoader { // 改变成二进制码 public static String[][] getPX(String args) { int[] rgb = new int[3]; File file = new File(args); BufferedImage bi = null; try { bi = ImageIO.read(file); } catch (Exception e) { e.printStackTrace(); } int width = bi.getWidth(); int height = bi.getHeight(); int minx = bi.getMinX(); int miny = bi.getMinY(); String[][] list = new String[width][height]; for (int i = minx; i < width; i++) { for (intj = miny; j < height; j++) { int pixel = bi.getRGB(i, j); rgb[0] = (pixel & 0xff0000) >> 16; rgb[1] = (pixel & 0xff00) >> 8; rgb[2] = (pixel & 0xff); list[i][j] = rgb[0] + "," + rgb[1] + "," + rgb[2]; } } return list; } public static void compareImage(String imgPath1, String imgPath2) { String[] images = {imgPath1, imgPath2}; if (images.length == 0) { System.out.println("Usage >java BMPLoader ImageFile.bmp"); System.exit(0); } // 分析图片相似度 begin String[][] list1 = getPX(images[0]); String[][] list2 = getPX(images[1]); int xiangsi = 0; int busi = 0; int i = 0, j = 0; for (String[] strings : list1) { if ((i + 1) == list1.length) { continue; } for (int m = 0; m < strings.length; m++) { try { String[] value1 = list1[i][j].toString().split(","); String[] value2 = list2[i][j].toString().split(","); int k = 0; for (int n = 0; n < value2.length; n++) { if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) { xiangsi++; } else { busi++; } } } catch (RuntimeException e) { continue; } j++; } i++; } list1 = getPX(images[1]); list2 = getPX(images[0]); i = 0; j = 0; for (String[] strings : list1) { if ((i + 1) == list1.length) { continue; } for (int m = 0; m < strings.length; m++) { try { String[] value1 = list1[i][j].toString().split(","); String[] value2 = list2[i][j].toString().split(","); int k = 0; for (int n = 0; n < value2.length; n++) { if (Math.abs(Integer.parseInt(value1[k]) - Integer.parseInt(value2[k])) < 5) { xiangsi++; } else { busi++; } } } catch (RuntimeException e) { continue; } j++; } i++; } String baifen = ""; try { baifen = ((Double.parseDouble(xiangsi + "") / Double.parseDouble((busi + xiangsi) + "")) + ""); baifen = baifen.substring(baifen.indexOf(".") + 1, baifen.indexOf(".") + 3); } catch (Exception e) { baifen = "0"; } if (baifen.length() <= 0) { baifen = "0"; } if (busi == 0) { baifen = "100"; } System.out.println("相似像素数量:" + xiangsi + " 不相似像素数量:" + busi + " 相似率: " + Integer.parseInt(baifen) + "%"); } } ``` ## . 顺序内聚:
一个模块的输出为另一个模块的输入
。 ```java if("samsung".equals(brand)||"IPhone".equals(brand)||"MI".equals(brand)||"huawei".equals(brand)){List
lists=dao.getPhoneByCompany(brand); String gson=getGson(lists);I //System.out.println(gson); out.write(gson); } public String getGson(List
lists){ Gson gson=new Gson(); return gson.toJson(lists); } ``` ## . 通信内聚: 一个模块中有多个函数,
操作同一数据集或者产生同一数据集
。 ```java class OrderListViewAdapter extends BaseAdapter { private List
orderItems; @Override public int getCount() { return orderItems.size(); } @Override public Object getItem(int position) { return orderItems.get(position); } } ``` ## . 过程内聚: 一个模块中存在多个函数,这几个函数
仅仅因为过程相关,可能并不公用数据
。 ```java package com.tkclm.persistence; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class DBUtil { private static final String URL = "jdbc:mysql://127.0.0.1:3306/tkclm"; private static final String USER = "root"; private static final String PASSWORD = "224404"; //连接数据库 public static Connection getConnection(){ Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(URL, USER, PASSWORD); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } //关闭数据库 public static void closeConnection(Connection connection) { if (connection != null) { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } } } ``` ## . 时间内聚: 一个模块完成的
相关的功能放在同一模块
中。 ```java package com.phonestore.domain; public class Account { /**_id 标识 account 自动增长*/ private int _id; /**和 password 共同识别一行元组*/ private String username; /**和 username 共同识别一行元组*/ private String password; /**邮箱地址*/ private String email; /**电话号码,可用于注册时进行验证码验证*/ private String tele; //时间内聚 public Account(int _id, String username, String password, String email, String tele) { super(); this._id = _id; this.username = username; this.password = password; this.email = email; this.tele = tele; } } ``` ## . 偶然内聚: 一个模块存在多个函数,各个函数之间毫无关系。 ```java package com.phonestore.persistence.test; import java.util.List; import org.junit.Test; import com.phonestore.domain.Phone; import com.phonestore.persistence.PhoneDAO; public class PhoneDAOTest { @Test public void testInsert(){ PhoneDAO dao = new PhoneDAO(); Phone phone = new Phone("小米 M4",2232,4.15, "小米","双卡双待,5.0 大屏", "/PhoneShopServer/image/xiaomi/小米 M4.jpg"); dao.addPhone(phone); } @Test public void testGetById(){ PhoneDAO dao = new PhoneDAO(); Phone phone = new Phone(); phone.set_id(1); Phone phone1 = dao.getPhoneById(phone); System.out.println(phone1.getName()); } @Test public void testUpdate(){ PhoneDAO dao = new PhoneDAO(); Phone phone = new Phone("Sony z1",4299,4.7, "sony","sony 13's best",null); phone.set_id(4); System.out.println(dao.update(phone));; } @Test public void testDelete(){ PhoneDAO dao = new PhoneDAO(); Phone phone = new Phone(); phone.set_id(4); dao.deleteAccountByID(phone ); } } ```
点赞
热门评论
最新评论
匿名用户
+1
-1
·
回复TA
暂无热门评论
相关推荐
阅读更多资讯
热门评论 最新评论
暂无热门评论