对类来说的,即一个类应该只负责一项职责。如类A负责两个不同的职责,职责1,职责2。当职责1需求变更而改变A时,可能造成职责2智行错误,所以要将类A的粒度分解为A1,A2
错误的应用实例
- package org.example.demo0;
- /**
- * @description: 单一职责原则
- * @author: abel.he
- * @date: 2023-07-31
- **/
- public class SingleResponsibility {
- public static void main(String[] args) {
- Vehicle vehicle = new Vehicle();
- vehicle.run("摩托车");
- vehicle.run("汽车");
- vehicle.run("飞机");
- }
- }
- class Vehicle {
- public void run(String vehicleName) {
- System.out.println(vehicleName + "在公路上运行");
- }
- }
复制代码 正确的实例
- package org.example.demo0;
- /**
- * @description: 单一职责原则(正确)
- * @author: abel.he
- * @date: 2023-07-31
- **/
- public class SingleResponsibilityCorrect {
- public static void main(String[] args) {
- Vehicle1 vehicle1 = new Vehicle1();
- vehicle1.run("小汽车");
- Air air = new Air();
- air.run("飞机");
-
- }
- }
- /**
- * 汽车工具类
- */
- class Vehicle1 {
- public void run(String vehicleName) {
- System.out.println(vehicleName + "在地上跑");
- }
- }
- class Air {
- public void run(String airName) {
- System.out.println(airName + "在天上飞");
- }
- }
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |