设计模式简记-设计原则之开闭原则

3.2 开闭原则

3.2.1 对扩展开放、对修改关闭

  • 详细表述

    在已有代码基础上扩展代码(新增模块、类、方法等),而非修改已有代码(修改模块、类、方法等)。

  • 实例

    API 接口监控告警的代码。

    • 其中,AlertRule 存储告警规则,可以自由设置。
    • Notification 是告警通知类,支持邮件、短信、微信、手机等多种通知渠道。NotificationEmergencyLevel 表示通知的紧急程度,包括 SEVERE(严重)、URGENCY(紧急)、NORMAL(普通)、TRIVIAL(无关紧要),不同的紧急程度对应不同的发送渠道。
    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, "...");
        }
      }
    }
    
    • 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, "...");
        }
      }
    }
    
    • 问题:
      • 一方面,我们对接口进行了修改,这就意味着调用这个接口的代码都要做相应的修改。
      • 另一方面,修改了 check() 函数,相应的单元测试都需要修改。
    • 重构
      • 第一部分是将 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, "...");
        }
      }
    }
    
    • 重构之后的 Alert 该如何使用呢?具体代码如下:其中,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() {
        instance.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);
      }
    }
    
    • 再来看下,基于重构之后的代码,如果再添加上面讲到的那个新功能,每秒钟接口超时请求个数超过某个最大阈值就告警,我们又该如何改动代码呢?主要的改动有下面四处。
      • 第一处改动是:在 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);
    }
    

3.2.2 修改代码就意味着违背开闭原则吗?

  • 必要纠结某个代码改动是“修改”还是“扩展”,更没必要太纠结它是否违反“开闭原则”。

    回到这条原则的设计初衷:只要它没有破坏原有的代码的正常运行,没有破坏原有的单元测试,就可以说,这是一个合格的代码改动。

  • 要认识到,添加一个新功能,不可能任何模块、类、方法的代码都不“修改”,这个是做不到的。类需要创建、组装、并且做一些初始化操作,才能构建成可运行的的程序,这部分代码的修改是在所难免的。

    要做的是尽量让修改操作更集中、更少、更上层,尽量让最核心、最复杂的那部分逻辑代码满足开闭原则

3.2.3 如何做到“对扩展开放、修改关闭”?

  • 要时刻具备扩展意识、抽象意识、封装意识。这些“潜意识”可能比任何开发技巧都重要

  • 支持开闭原则的一些更加具体的方法论:

    • 在众多的设计原则、思想、模式中,最常用来提高代码扩展性的方法有:多态、依赖注入、基于接口而非实现编程,以及大部分的设计模式(比如,装饰、策略、模板、职责链、状态等)。

    • 多态、依赖注入、基于接口而非实现编程,以及前面提到的抽象意识,说的都是同一种设计思路,只是从不同的角度、不同的层面来阐述而已。这也体现了“很多设计原则、思想、模式都是相通的”这一思想。

  • 通过一个例子来解释一下,如何利用这几个设计思想或原则来实现“对扩展开放、对修改关闭”。

    比如,代码中通过 Kafka 来发送异步消息。对于这样一个功能的开发,我们要学会将其抽象成一组跟具体消息队列(Kafka)无关的异步消息接口。所有上层系统都依赖这组抽象的接口编程,并且通过依赖注入的方式来调用。当我们要替换新的消息队列的时候,比如将 Kafka 替换成 RocketMQ,可以很方便地拔掉老的消息队列实现,插入新的消息队列实现。具体代码如下所示:

    // 这一部分体现了抽象意识
    public interface MessageQueue { //... }
    public class KafkaMessageQueue implements MessageQueue { //... }
    public class RocketMQMessageQueue implements MessageQueue {//...}
    
    public interface MessageFormatter { //... }
    public class JsonMessageFormatter implements MessageFormatter {//...}
    public class MessageFormatter implements MessageFormatter {//...}
    
    public class Demo {
      private MessageQueue msgQueue; // 基于接口而非实现编程
      public Demo(MessageQueue msgQueue) { // 依赖注入
        this.msgQueue = msgQueue;
      }
      
      // msgFormatter:多态、依赖注入
      public void sendNotification(Notification notification, MessageFormatter msgFormatter) {
        //...    
      }
    }
    

3.2.4 如何在项目中灵活应用

  • 对于一些比较确定的、短期内可能就会扩展,或者需求改动对代码结构影响比较大的情况,或者实现成本不高的扩展点,在编写代码的时候之后,我们就可以事先做些扩展性设计

  • 开闭原则也并不是免费的。有些情况下,代码的扩展性会跟可读性相冲突。

    之前举的 Alert 告警的例子中,如果告警规则并不是很多、也不复杂,那 check() 函数中的 if 语句就不会很多,代码逻辑也不复杂,代码行数也不多,那最初的第一种代码实现思路简单易读,就是比较合理的选择。

猜你喜欢

转载自www.cnblogs.com/wod-Y/p/12625629.html