设计模式简记-设计原则之接口隔离原则

3.4 接口隔离原则

3.4.1 如何理解“接口隔离原则”?

  • 英文翻译是“ Interface Segregation Principle”,缩写为 ISP。

    Robert Martin 在 SOLID 原则中是这样定义它的:“Clients should not be forced to depend upon interfaces that they do not use。”直译成中文的话就是:客户端不应该强迫依赖它不需要的接口。其中的“客户端”,可以理解为接口的调用者或者使用者。

  • 在这条原则中,我们可以把“接口”理解为下面三种东西:

    • 一组 API 接口集合
    • 单个 API 接口或函数
    • OOP 中的接口概念

3.4.2 把“接口”理解为一组 API 接口集合

  • 微服务用户系统提供了一组跟用户相关的 API 给其他系统使用,比如:注册、登录、获取用户信息等。具体代码如下所示:

    public interface UserService {
      boolean register(String cellphone, String password);
      boolean login(String cellphone, String password);
      UserInfo getUserInfoById(long id);
      UserInfo getUserInfoByCellphone(String cellphone);
    }
    
    public class UserServiceImpl implements UserService {
      //...
    }
    

    现在,我们的后台管理系统要实现删除用户的功能,希望用户系统提供一个删除用户的接口。这个时候我们该如何来做呢?

    最好的解决方案是从架构设计的层面,通过接口鉴权的方式来限制接口的调用。不过,如果暂时没有鉴权框架来支持,我们还可以从代码设计的层面,尽量避免接口被误用。我们参照接口隔离原则,调用者不应该强迫依赖它不需要的接口,将删除接口单独放到另外一个接口 RestrictedUserService 中,然后将 RestrictedUserService 只打包提供给后台管理系统来使用。具体的代码实现如下所示:

    public interface UserService {
      boolean register(String cellphone, String password);
      boolean login(String cellphone, String password);
      UserInfo getUserInfoById(long id);
      UserInfo getUserInfoByCellphone(String cellphone);
    }
    
    public interface RestrictedUserService {
      boolean deleteUserByCellphone(String cellphone);
      boolean deleteUserById(long id);
    }
    
    public class UserServiceImpl implements UserService, RestrictedUserService {
      // ...省略实现代码...
    }
    

3.4.3 把“接口”理解为单个 API 接口或函数

  • 把接口理解为单个接口或函数。那接口隔离原则就可以理解为:函数的设计要功能单一,不要将多个不同的功能逻辑在一个函数中实现。

    public class Statistics {
      private Long max;
      private Long min;
      private Long average;
      private Long sum;
      private Long percentile99;
      private Long percentile999;
      //...省略constructor/getter/setter等方法...
    }
    
    public Statistics count(Collection<Long> dataSet) {
      Statistics statistics = new Statistics();
      //...省略计算逻辑...
      return statistics;
    }
    

    上面的代码中,count() 函数的功能不够单一,包含很多不同的统计功能,比如,求最大值、最小值、平均值等等。按照接口隔离原则,我们应该把 count() 函数拆成几个更小粒度的函数,每个函数负责一个独立的统计功能。拆分之后的代码如下所示:

    public Long max(Collection<Long> dataSet) { //... }
    public Long min(Collection<Long> dataSet) { //... } 
    public Long average(Colletion<Long> dataSet) { //... }
    // ...省略其他统计函数...
    
  • 在某种意义上讲,count() 函数也不能算是职责不够单一,毕竟它做的事情只跟统计相关。我们在讲单一职责原则的时候,也提到过类似的问题。实际上,判定功能是否单一,除了很强的主观性,还需要结合具体的场景:

    如果在项目中,对每个统计需求,Statistics 定义的那几个统计信息都有涉及,那 count() 函数的设计就是合理的。相反,如果每个统计需求只涉及 Statistics 罗列的统计信息中一部分,则count()函数的设计就不合理。

3.4.4 把“接口”理解为 OOP 中的接口概念

  • 例子

    假设项目中用到了三个外部系统:Redis、MySQL、Kafka。每个系统都对应一系列配置信息,比如地址、端口、访问超时时间等。为了在内存中存储这些配置信息,供项目中的其他模块来使用,分别设计实现了三个 Configuration 类:RedisConfig、MysqlConfig、KafkaConfig。具体的代码实现如下所示:

    public class RedisConfig {
        private ConfigSource configSource; //配置中心(比如zookeeper)
        private String address;
        private int timeout;
        private int maxTotal;
        //省略其他配置: maxWaitMillis,maxIdle,minIdle...
    
        public RedisConfig(ConfigSource configSource) {
            this.configSource = configSource;
        }
    
        public String getAddress() {
            return this.address;
        }
        //...省略其他get()、init()方法...
    
        public void update() {
          //从configSource加载配置到address/timeout/maxTotal...
        }
    }
    
    public class KafkaConfig { //...省略... }
    public class MysqlConfig { //...省略... }
    
    • 现在,有一个新的功能需求,希望支持 Redis 和 Kafka 配置信息的热更新。所谓“热更新(hot update)”就是,如果在配置中心中更改了配置信息,我们希望在不用重启系统的情况下,能将最新的配置信息加载到内存中(也就是 RedisConfig、KafkaConfig 类中)。但是,因为某些原因,我们并不希望对 MySQL 的配置信息进行热更新。

      为了实现这样一个功能需求,设计实现了一个 ScheduledUpdater 类,以固定时间频率(periodInSeconds)来调用 RedisConfig、KafkaConfig 的 update() 方法更新配置信息。具体的代码实现如下所示:

    public interface Updater {
      void update();
    }
    
    public class RedisConfig implemets Updater {
      //...省略其他属性和方法...
      @Override
      public void update() { //... }
    }
    
    public class KafkaConfig implements Updater {
      //...省略其他属性和方法...
      @Override
      public void update() { //... }
    }
    
    public class MysqlConfig { //...省略其他属性和方法... }
    
    public class ScheduledUpdater {
        private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();;
        private long initialDelayInSeconds;
        private long periodInSeconds;
        private Updater updater;
    
        public ScheduleUpdater(Updater updater, long initialDelayInSeconds, long periodInSeconds) {
            this.updater = updater;
            this.initialDelayInSeconds = initialDelayInSeconds;
            this.periodInSeconds = periodInSeconds;
        }
    
        public void run() {
            executor.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    updater.update();
                }
            }, this.initialDelayInSeconds, this.periodInSeconds, TimeUnit.SECONDS);
        }
    }
    
    public class Application {
      ConfigSource configSource = new ZookeeperConfigSource(/*省略参数*/);
      public static final RedisConfig redisConfig = new RedisConfig(configSource);
      public static final KafkaConfig kafkaConfig = new KakfaConfig(configSource);
      public static final MySqlConfig mysqlConfig = new MysqlConfig(configSource);
    
      public static void main(String[] args) {
        ScheduledUpdater redisConfigUpdater = new ScheduledUpdater(redisConfig, 300, 300);
        redisConfigUpdater.run();
        
        ScheduledUpdater kafkaConfigUpdater = new ScheduledUpdater(kafkaConfig, 60, 60);
        redisConfigUpdater.run();
      }
    }
    
    • 现在,又有了一个新的监控功能需求。通过命令行来查看 Zookeeper 中的配置信息是比较麻烦的。所以,我们希望能有一种更加方便的配置信息查看方式。可以在项目中开发一个内嵌的 SimpleHttpServer,输出项目的配置信息到一个固定的 HTTP 地址,比如:http://127.0.0.1:2389/config 。只需要在浏览器中输入这个地址,就可以显示出系统的配置信息。不过,出于某些原因,我们只想暴露 MySQL 和 Redis 的配置信息,不想暴露 Kafka 的配置信息。

      public interface Updater {
        void update();
      }
      
      public interface Viewer {
        String outputInPlainText();
        Map<String, String> output();
      }
      
      public class RedisConfig implemets Updater, Viewer {
        //...省略其他属性和方法...
        @Override
        public void update() { //... }
        @Override
        public String outputInPlainText() { //... }
        @Override
        public Map<String, String> output() { //...}
      }
      
      public class KafkaConfig implements Updater {
        //...省略其他属性和方法...
        @Override
        public void update() { //... }
      }
      
      public class MysqlConfig implements Viewer {
        //...省略其他属性和方法...
        @Override
        public String outputInPlainText() { //... }
        @Override
        public Map<String, String> output() { //...}
      }
      
      public class SimpleHttpServer {
        private String host;
        private int port;
        private Map<String, List<Viewer>> viewers = new HashMap<>();
        
        public SimpleHttpServer(String host, int port) {//...}
        
        public void addViewers(String urlDirectory, Viewer viewer) {
          if (!viewers.containsKey(urlDirectory)) {
            viewers.put(urlDirectory, new ArrayList<Viewer>());
          }
          this.viewers.get(urlDirectory).add(viewer);
        }
        
        public void run() { //... }
      }
      
      public class Application {
          ConfigSource configSource = new ZookeeperConfigSource();
          public static final RedisConfig redisConfig = new RedisConfig(configSource);
          public static final KafkaConfig kafkaConfig = new KakfaConfig(configSource);
          public static final MySqlConfig mysqlConfig = new MySqlConfig(configSource);
          
          public static void main(String[] args) {
              ScheduledUpdater redisConfigUpdater =
                  new ScheduledUpdater(redisConfig, 300, 300);
              redisConfigUpdater.run();
              
              ScheduledUpdater kafkaConfigUpdater =
                  new ScheduledUpdater(kafkaConfig, 60, 60);
              redisConfigUpdater.run();
              
              SimpleHttpServer simpleHttpServer = new SimpleHttpServer(“127.0.0.1”, 2389);
              simpleHttpServer.addViewer("/config", redisConfig);
              simpleHttpServer.addViewer("/config", mysqlConfig);
              simpleHttpServer.run();
          }
      }
      
    • 回顾一下这个例子的设计思想。我们设计了两个功能非常单一的接口:Updater 和 Viewer。ScheduledUpdater 只依赖 Updater 这个跟热更新相关的接口,不需要被强迫去依赖不需要的 Viewer 接口,满足接口隔离原则。同理,SimpleHttpServer 只依赖跟查看信息相关的 Viewer 接口,不依赖不需要的 Updater 接口,也满足接口隔离原则。

3.4.5 总结

  • 如何理解“接口隔离原则”?

    理解“接口隔离原则”的重点是理解其中的“接口”二字。这里有三种不同的理解。

    • 如果把“接口”理解为一组接口集合,可以是某个微服务的接口,也可以是某个类库的接口等。如果部分接口只被部分调用者使用,我们就需要将这部分接口隔离出来,单独给这部分调用者使用,而不强迫其他调用者也依赖这部分不会被用到的接口。
    • 如果把“接口”理解为单个 API 接口或函数,部分调用者只需要函数中的部分功能,那我们就需要把函数拆分成粒度更细的多个函数,让调用者只依赖它需要的那个细粒度函数。
    • 如果把“接口”理解为 OOP 中的接口,也可以理解为面向对象编程语言中的接口语法。那接口的设计要尽量单一,不要让接口的实现类和调用者,依赖不需要的接口函数。
  • 接口隔离原则与单一职责原则的区别

    单一职责原则针对的是模块、类、接口的设计。

    接口隔离原则相对于单一职责原则,一方面更侧重于接口的设计,另一方面它的思考角度也是不同的。

    接口隔离原则提供了一种判断接口的职责是否单一的标准:通过调用者如何使用接口来间接地判定。如果调用者只使用部分接口或接口的部分功能,那接口的设计就不够职责单一。

原文地址:https://www.cnblogs.com/wod-Y/p/12655773.html