随笔 - 1162  文章 - 0  评论 - 16  阅读 - 59万 

单一职责原则(Single Responsibility Principle)

一、基本介绍

  对类来说,即一个类应该只负责一项职责。

  如类 A 负责两个不同的职责:职责1,职责2。当职责1需求变更而改变 A时,可能造成职责 2 执行错误,所以需要将 类 A 的粒度分解为 A1, A2。

二、应用实例

  下面以交通工具为案例学习:

  1、方案一

复制代码
 1 public class SingleResponsibility1 {
 2     public static void main(String[] args) {
 3         Vehicle vehicle = new Vehicle();
 4         vehicle.run("摩托车");
 5         vehicle.run("飞机");
 6         vehicle.run("轮船");
 7     }
 8 
 9 }
10 
11 /**
12  * 交通工具类
13  * 方式一:
14  * 1、在方式一的 run 方法中,违反了单一职责原则
15  * 2、解决的方案非常的简单,根据交通工具运行方法不同,分解成不同的类即可
16  */
17 class Vehicle {
18 
19     public void run(String vehicle) {
20         System.out.println(vehicle + "在公路上跑");
21     }
22 
23 }
复制代码

 

  2、方案二:类级别遵守单一职责

复制代码
 1 public class SingleResponsibility2 {
 2     public static void main(String[] args) {
 3         RoadVehicle roadVehicle = new RoadVehicle();
 4         roadVehicle.run("摩托车");
 5         roadVehicle.run("汽车");
 6 
 7         AirVehicle airVehicle = new AirVehicle();
 8         airVehicle.run("飞机");
 9     }
10 }
11 /**
12  * 方案2的分析
13  *  1、遵守单一职责原则
14  *  2、但是这样做的改动很大,即将类分解,同时修改客户端
15  *  3、改进:直接修改 Vehicle类,改动的代码比较少 =》方案3
16  */
17 
18 /**
19  * 路上的交通工具
20  */
21 class RoadVehicle {
22     public void run(String vehicle) {
23         System.out.println(vehicle + "在公路运行");
24     }
25 }
26 
27 class AirVehicle {
28     public void run(String vehicle) {
29         System.out.println(vehicle + "在天空运行");
30     }
31 }
32 
33 class WatchVehicle {
34     public void run(String vehicle) {
35         System.out.println(vehicle + "在水中运行");
36     }
37 }
复制代码

 

 

  3、方案三:方法级别遵守单一职责

复制代码
 1 public class SingleResponsibility3 {
 2     public static void main(String[] args) {
 3         Vehicle2 vehicle2 = new Vehicle2();
 4         vehicle2.run("汽车");
 5         vehicle2.runWater("轮船");
 6         vehicle2.runAir("飞机");
 7     }
 8 }
 9 
10 /**
11  * 方式3的分析
12  * 1、这里修改方法没有对原来的类做大的修改,只是增加方法
13  * 2、这里虽然没有在类这个级别上遵守单一职责原则,但是在方法级别上,仍然是单一职责
14  */
15 class Vehicle2 {
16 
17     public void run(String vehicle) {
18         System.out.println(vehicle + "在公路上运行。。。");
19     }
20 
21     public void runAir(String vehicle) {
22         System.out.println(vehicle + "在空中运行。。。");
23     }
24 
25     public void runWater(String vehicle) {
26         System.out.println(vehicle + "在公路上运行。。。");
27     }
28 }
复制代码

 

 

三、总结

  1、降低类的复杂度,一个类只负责一项职责;

  2、提供类的可读性,可维护性;

  3、降低变更引起的风险;

  4、通常情况下,我们应该遵守单一职责原则,只有逻辑足够简单,才可以在代码级违反单一职责原则;

    只有类中方法数量足够少,可以在方法级别保持单一职责原则;

 

posted on   格物致知_Tony  阅读(237)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示

目录导航