找回密码
 立即注册
首页 业界区 业界 设计模式原则之:单一职责模式

设计模式原则之:单一职责模式

梁丘艷蕙 2025-6-8 22:25:15
  对类来说的,即一个类应该只负责一项职责。如类A负责两个不同的职责,职责1,职责2。当职责1需求变更而改变A时,可能造成职责2智行错误,所以要将类A的粒度分解为A1,A2
错误的应用实例
  1. package org.example.demo0;
  2. /**
  3. * @description: 单一职责原则
  4. * @author: abel.he
  5. * @date: 2023-07-31
  6. **/
  7. public class SingleResponsibility {
  8.     public static void main(String[] args) {
  9.         Vehicle vehicle = new Vehicle();
  10.         vehicle.run("摩托车");
  11.         vehicle.run("汽车");
  12.         vehicle.run("飞机");
  13.     }
  14. }
  15. class Vehicle {
  16.     public void run(String vehicleName) {
  17.         System.out.println(vehicleName + "在公路上运行");
  18.     }
  19. }
复制代码
正确的实例
  1. package org.example.demo0;
  2. /**
  3. * @description: 单一职责原则(正确)
  4. * @author: abel.he
  5. * @date: 2023-07-31
  6. **/
  7. public class SingleResponsibilityCorrect {
  8.     public static void main(String[] args) {
  9.         Vehicle1 vehicle1 = new Vehicle1();
  10.         vehicle1.run("小汽车");
  11.         Air air = new Air();
  12.         air.run("飞机");
  13.         
  14.     }
  15. }
  16. /**
  17. * 汽车工具类
  18. */
  19. class Vehicle1 {
  20.     public void run(String vehicleName) {
  21.         System.out.println(vehicleName + "在地上跑");
  22.     }
  23. }
  24. class Air {
  25.     public void run(String airName) {
  26.         System.out.println(airName + "在天上飞");
  27.     }
  28. }
复制代码
  

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册