• 一个重构:开闭原则案例


    原始代码

    public class Alert {
      private AlertRule rule;
      private Notification notification;
    
      public Alert(AlertRule rule, Notification notification) {
        this.rule = rule;
        this.notification = notification;
      }
    
      public void check(String api, long requestCount, long errorCount, long durationOfSeconds) {
        long tps = requestCount / durationOfSeconds;
        if (tps > rule.getMatchedRule(api).getMaxTps()) {
          notification.notify(NotificationEmergencyLevel.URGENCY, "...");
        }
        if (errorCount > rule.getMatchedRule(api).getMaxErrorCount()) {
          notification.notify(NotificationEmergencyLevel.SEVERE, "...");
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    上面这段代码非常简单,业务逻辑主要集中在 check() 函数中。
    当接口的 TPS 超过某个预先设置的最大值时,以及当接口请求出错数大于某个最大允许值时,就会触发告警,通知接口的相关负责人或者团队。

    增加新功能(基于修改)

    现在,如果我们需要添加一个功能,当每秒钟接口超时请求个数,超过某个预先设置的最大阈值时,我们也要触发告警发送通知。这个时候,我们该如何改动代码呢?主要的改动有两处:第一处是修改 check() 函数的入参,添加一个新的统计数据 timeoutCount,表示超时接口请求数;第二处是在 check() 函数中添加新的告警逻辑。具体的代码改动如下所示:

    public class Alert {
      // ...省略AlertRule/Notification属性和构造函数...
      
      // 改动一:添加参数timeoutCount
      public void check(String api, long requestCount, long errorCount, long timeoutCount, long durationOfSeconds) {
        long tps = requestCount / durationOfSeconds;
        if (tps > rule.getMatchedRule(api).getMaxTps()) {
          notification.notify(NotificationEmergencyLevel.URGENCY, "...");
        }
        if (errorCount > rule.getMatchedRule(api).getMaxErrorCount()) {
          notification.notify(NotificationEmergencyLevel.SEVERE, "...");
        }
        // 改动二:添加接口超时处理逻辑
        long timeoutTps = timeoutCount / durationOfSeconds;
        if (timeoutTps > rule.getMatchedRule(api).getMaxTimeoutTps()) {
          notification.notify(NotificationEmergencyLevel.URGENCY, "...");
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    这样的代码修改实际上存在挺多问题的。一方面,我们对接口进行了修改,这就意味着调用这个接口的代码都要做相应的修改。另一方面,修改了 check() 函数,相应的单元测试都需要修改。

    上面的代码改动是基于“修改”的方式来实现新功能的。如果我们遵循开闭原则,也就是“对扩展开放、对修改关闭”。那如何通过“扩展”的方式,来实现同样的功能呢?

    重构版(基于扩展)

    我们先重构一下之前的 Alert 代码,让它的扩展性更好一些。
    重构的内容主要包含两部分:第一部分是将 check() 函数的多个入参封装成 ApiStatInfo 类;第二部分是引入 handler 的概念,将 if 判断逻辑分散在各个 handler 中。

    public class Alert {
      private List<AlertHandler> alertHandlers = new ArrayList<>();
      
      public void addAlertHandler(AlertHandler alertHandler) {
        this.alertHandlers.add(alertHandler);
      }
    
      public void check(ApiStatInfo apiStatInfo) {
        for (AlertHandler handler : alertHandlers) {
          handler.check(apiStatInfo);
        }
      }
    }
    
    public class ApiStatInfo {//省略constructor/getter/setter方法
      private String api;
      private long requestCount;
      private long errorCount;
      private long durationOfSeconds;
    }
    
    public abstract class AlertHandler {
      protected AlertRule rule;
      protected Notification notification;
      public AlertHandler(AlertRule rule, Notification notification) {
        this.rule = rule;
        this.notification = notification;
      }
      public abstract void check(ApiStatInfo apiStatInfo);
    }
    
    public class TpsAlertHandler extends AlertHandler {
      public TpsAlertHandler(AlertRule rule, Notification notification) {
        super(rule, notification);
      }
    
      @Override
      public void check(ApiStatInfo apiStatInfo) {
        long tps = apiStatInfo.getRequestCount()/ apiStatInfo.getDurationOfSeconds();
        if (tps > rule.getMatchedRule(apiStatInfo.getApi()).getMaxTps()) {
          notification.notify(NotificationEmergencyLevel.URGENCY, "...");
        }
      }
    }
    
    public class ErrorAlertHandler extends AlertHandler {
      public ErrorAlertHandler(AlertRule rule, Notification notification){
        super(rule, notification);
      }
    
      @Override
      public void check(ApiStatInfo apiStatInfo) {
        if (apiStatInfo.getErrorCount() > rule.getMatchedRule(apiStatInfo.getApi()).getMaxErrorCount()) {
          notification.notify(NotificationEmergencyLevel.SEVERE, "...");
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    其中,ApplicationContext 是一个单例类,负责 Alert 的创建、组装(alertRule 和 notification 的依赖注入)、初始化(添加 handlers)工作。

    public class ApplicationContext {
      private AlertRule alertRule;
      private Notification notification;
      private Alert alert;
      
      public void initializeBeans() {
        alertRule = new AlertRule(/*.省略参数.*/); //省略一些初始化代码
        notification = new Notification(/*.省略参数.*/); //省略一些初始化代码
        alert = new Alert();
        alert.addAlertHandler(new TpsAlertHandler(alertRule, notification));
        alert.addAlertHandler(new ErrorAlertHandler(alertRule, notification));
      }
      public Alert getAlert() { return alert; }
    
      // 饿汉式单例
      private static final ApplicationContext instance = new ApplicationContext();
      private ApplicationContext() {
        initializeBeans();
      }
      public static ApplicationContext getInstance() {
        return instance;
      }
    }
    
    public class Demo {
      public static void main(String[] args) {
        ApiStatInfo apiStatInfo = new ApiStatInfo();
        // ...省略设置apiStatInfo数据值的代码
        ApplicationContext.getInstance().getAlert().check(apiStatInfo);
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    基于重构之后的代码,如果再添加上面讲到的那个新功能,每秒钟接口超时请求个数超过某个最大阈值就告警,我们又该如何改动代码呢?
    主要的改动有下面四处。
    第一处改动是:在 ApiStatInfo 类中添加新的属性 timeoutCount。
    第二处改动是:添加新的 TimeoutAlertHander 类。
    第三处改动是:在 ApplicationContext 类的 initializeBeans() 方法中,往 alert 对象中注册新的 timeoutAlertHandler。
    第四处改动是:在使用 Alert 类的时候,需要给 check() 函数的入参 apiStatInfo 对象设置 timeoutCount 的值。

    public class Alert { // 代码未改动... }
    public class ApiStatInfo {//省略constructor/getter/setter方法
      private String api;
      private long requestCount;
      private long errorCount;
      private long durationOfSeconds;
      private long timeoutCount; // 改动一:添加新字段
    }
    public abstract class AlertHandler { //代码未改动... }
    public class TpsAlertHandler extends AlertHandler {//代码未改动...}
    public class ErrorAlertHandler extends AlertHandler {//代码未改动...}
    // 改动二:添加新的handler
    public class TimeoutAlertHandler extends AlertHandler {//省略代码...}
    
    public class ApplicationContext {
      private AlertRule alertRule;
      private Notification notification;
      private Alert alert;
      
      public void initializeBeans() {
        alertRule = new AlertRule(/*.省略参数.*/); //省略一些初始化代码
        notification = new Notification(/*.省略参数.*/); //省略一些初始化代码
        alert = new Alert();
        alert.addAlertHandler(new TpsAlertHandler(alertRule, notification));
        alert.addAlertHandler(new ErrorAlertHandler(alertRule, notification));
        // 改动三:注册handler
        alert.addAlertHandler(new TimeoutAlertHandler(alertRule, notification));
      }
      //...省略其他未改动代码...
    }
    
    public class Demo {
      public static void main(String[] args) {
        ApiStatInfo apiStatInfo = new ApiStatInfo();
        // ...省略apiStatInfo的set字段代码
        apiStatInfo.setTimeoutCount(289); // 改动四:设置tiemoutCount值
        ApplicationContext.getInstance().getAlert().check(apiStatInfo);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    重构之后的代码更加灵活和易扩展。如果我们要想添加新的告警逻辑,只需要基于扩展的方式创建新的 handler 类即可,不需要改动原来的 check() 函数的逻辑。而且,我们只需要为新的 handler 类添加单元测试,老的单元测试都不会失败,也不用修改。

  • 相关阅读:
    Web前端一套全部清晰 ① 学习路线
    FPGA 串口多字节发送,串口回环测试
    负载均衡 —— SpringCloud Netflix Ribbon
    遍历的几种方式
    【java】【SpringBoot】【一】基础篇 SpringBoot工程创建和实现ssm/ssmp整合
    java简单的实现socket浏览器返回数据
    对比学习系列(三)-----SimCLR
    数据结构<1>时空复杂度详解
    ssm+vue的台球厅管理系统(有报告)。Javaee项目,ssm vue前后端分离项目。
    Java实现各种加密验证算法(MD5、SHA256、base64、pdkdf2、pdkdf2_sha256)
  • 原文地址:https://blog.csdn.net/gaochubusheng/article/details/132819621