【设计模式之美】 SOLID 原则之四:接口隔离原则有哪三种应用?原则中的“接口”该如何理解?

本文主要是介绍【设计模式之美】 SOLID 原则之四:接口隔离原则有哪三种应用?原则中的“接口”该如何理解?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 一. 如何理解“接口隔离原则”?
  • 二. 接口隔离的三个情况
    • 1. 把“接口”理解为一组 API 接口集合
    • 2. 把“接口”理解为单个 API 接口或函数 ing(能够使用的场景并未理解)
    • 3. 把“接口”理解为 OOP 中的接口概念

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

客户端不应该被强迫依赖它不需要的接口(简单的理解:不在原有接口的增加方法)。其中的“客户端”,可以理解为接口的调用者或者使用者。

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

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

接下来从这三个方面举例说明,接口隔离的具体应用

 

二. 接口隔离的三个情况

1. 把“接口”理解为一组 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 {//...
}

现在,我们的后台管理系统要实现删除用户的功能,希望用户系统提供一个删除用户的接口。

 

违背接口隔离的方案

只需要在 UserService 中新添加一个 deleteUserByCellphone() 或 deleteUserById() 接口就可以了。这个方法可以解决问题,但是也隐藏了一些安全隐患。
删除用户是一个非常慎重的操作,我们只希望通过后台管理系统来执行,所以这个接口只限于给后台管理系统使用。如果我们把它放到 UserService 中,那所有使用到 UserService 的系统,都可以调用这个接口。不加限制地被其他业务系统调用,就有可能导致误删用户。
当然,最好的解决方案是从架构设计的层面,通过接口鉴权的方式来限制接口的调用。不过,如果暂时没有鉴权框架来支持,我们还可以从代码设计的层面,尽量避免接口被误用。

 

参照接口隔离原则

调用者不应该强迫依赖它不需要的接口,那么我们将删除接口单独放到另外一个接口中,然后将接口只打包(即只是UserServiceImpl集成新增接口)提供给后台管理系统来使用。

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 {// ...省略实现代码...
}

 
小结


在设计微服务或者类库接口的时候,如果部分接口只被部分调用者使用,那我们就需要将这部分接口隔离出来,单独给对应的调用者使用,而不是强迫其他调用者也依赖这部分不会被用到的接口。


 

2. 把“接口”理解为单个 API 接口或函数 ing(能够使用的场景并未理解)

把接口理解为单个(接口或)函数(以下为了方便讲解,我都简称为“函数”)。那接口隔离原则就可以理解为:函数的设计要功能单一,不要将多个不同的功能逻辑在一个函数中实现。

接下来,我们还是通过一个例子来解释一下。

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() 函数拆成几个更小粒度的函数,每个函数负责一个独立的统计功能。
  • 代码实现可能通过if else、Switch、函数式接口等。

拆分之后的代码如下所示:

public Long max(Collection<Long> dataSet) { //... }
public Long min(Collection<Long> dataSet) { //... } 
public Long average(Colletion<Long> dataSet) { //... }
// ...省略其他统计函数...

接口隔离原则跟单一职责原则有点类似,不过稍微还是有点区别。

单一职责原则针对的是模块、类、接口的设计。而接口隔离原则相对于单一职责原则,一方面它更侧重于接口的设计,另一方面它的思考的角度不同。它提供了一种判断接口是否职责单一的标准:通过调用者如何使用接口来间接地判定。如果调用者只使用部分接口或接口的部分功能,那接口的设计就不够职责单一。

 

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

假设我们的项目中用到了三个外部系统:Redis、MySQL、Kafka。

每个系统都对应一系列配置信息,比如地址、端口、访问超时时间等。为了在内存中存储这些配置信息,供项目中的其他模块来使用,我们分别设计实现了三个 Configuration 类:RedisConfig、MysqlConfig、KafkaConfig。

这里给出了 RedisConfig 的代码实现,另外两个类似。

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 { //...省略... }

新需求1
支持 Redis 和 Kafka 配置信息的热更新,但并不希望对 MySQL 的配置信息进行热更新。

所谓“热更新(hot update)”就是,如果在配置中心中更改了配置信息,我们希望在不用重启系统的情况下,能将最新的配置信息加载到内存中(也就是 RedisConfig、KafkaConfig 类中)。

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

public interface Updater {void update();
}// mysql不想热更新,所有没有实现接口
public class RedisConfig implemets Updater {//...省略其他属性和方法...@Overridepublic void update() { //... }
}public class KafkaConfig implements Updater {//...省略其他属性和方法...@Overridepublic 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() {@Overridepublic 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);kafkaConfigUpdater.run();}
}

 
新增需求二:新增监控功能

我们可以在项目中开发一个内嵌的 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();
}//三个类都实现Viewer监控接口
public class RedisConfig implemets Updater, Viewer {//...省略其他属性和方法...@Overridepublic void update() { //... }@Overridepublic String outputInPlainText() { //... }@Overridepublic Map<String, String> output() { //...}
}public class KafkaConfig implements Updater {//...省略其他属性和方法...@Overridepublic void update() { //... }
}public class MysqlConfig implements Viewer {//...省略其他属性和方法...@Overridepublic String outputInPlainText() { //... }@Overridepublic 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);//run:更新配置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 接口,也满足接口隔离原则。

 

不按照接口隔离原则设计

设计一个大而全的 Config 接口,让 RedisConfig、KafkaConfig、MysqlConfig 都实现这个 Config 接口,并且将原来传递给 ScheduledUpdater 的 Updater 和传递给 SimpleHttpServer 的 Viewer,都替换为 Config。

public interface Config {void update();String outputInPlainText();Map<String, String> output();
}public class RedisConfig implements Config {//...需要实现Config的三个接口update/outputIn.../output
}public class KafkaConfig implements Config {//...需要实现Config的三个接口update/outputIn.../output
}public class MysqlConfig implements Config {//...需要实现Config的三个接口update/outputIn.../output
}public class ScheduledUpdater {//...省略其他属性和方法..private Config config;public ScheduleUpdater(Config config, long initialDelayInSeconds, long periodInSeconds) {this.config = config;//...}//...
}public class SimpleHttpServer {private String host;private int port;private Map<String, List<Config>> viewers = new HashMap<>();public SimpleHttpServer(String host, int port) {//...}public void addViewer(String urlDirectory, Config config) {if (!viewers.containsKey(urlDirectory)) {viewers.put(urlDirectory, new ArrayList<Config>());}viewers.get(urlDirectory).add(config);}public void run() { //... }
}

这样的设计思路也是能工作的,但是对比前后两个设计思路,在同样的代码量、实现复杂度、同等可读性的情况下,第一种设计思路显然要比第二种好很多。为什么这么说呢?主要有两点原因。

  1. 第一种设计思路更加灵活、易扩展、易复用。

因为 Updater、Viewer 职责更加单一,单一就意味了通用、复用性好。
 
比如,我们现在又有一个新的需求,开发一个 Metrics 性能统计模块,并且希望将 Metrics 也通过 SimpleHttpServer 显示在网页上,以方便查看。这个时候,尽管 Metrics 跟 RedisConfig 等没有任何关系,但我们仍然可以让 Metrics 类实现非常通用的 Viewer 接口,复用 SimpleHttpServer 的代码实现。如下:

public class ApiMetrics implements Viewer {//...}
public class DbMetrics implements Viewer {//...}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 final ApiMetrics apiMetrics = new ApiMetrics();public static final DbMetrics dbMetrics = new DbMetrics();public static void main(String[] args) {SimpleHttpServer simpleHttpServer = new SimpleHttpServer(127.0.0.1, 2389);simpleHttpServer.addViewer("/config", redisConfig);simpleHttpServer.addViewer("/config", mySqlConfig);simpleHttpServer.addViewer("/metrics", apiMetrics);simpleHttpServer.addViewer("/metrics", dbMetrics);simpleHttpServer.run();}
}

 

  1. 第二种设计思路在代码实现上做了一些无用功。
  • 因为 Config 接口中包含两类不相关的接口,一类是 update(),一类是 output() 和 outputInPlainText()。
  • 理论上,KafkaConfig 只需要实现 update() 接口,并不需要实现 output() 相关的接口。同理,MysqlConfig 只需要实现 output() 相关接口,并需要实现 update() 接口。但第二种设计思路要求 RedisConfig、KafkaConfig、MySqlConfig 必须同时实现 Config 的所有接口函数(update、output、outputInPlainText)。
  • 除此之外,如果我们要往 Config 中继续添加一个新的接口,那所有的实现类都要改动。相反,如果我们的接口粒度比较小,那涉及改动的类就比较少。

 

参考:《设计模式之美》 – 王争

这篇关于【设计模式之美】 SOLID 原则之四:接口隔离原则有哪三种应用?原则中的“接口”该如何理解?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/583747

相关文章

Redis实现延迟任务的三种方法详解

《Redis实现延迟任务的三种方法详解》延迟任务(DelayedTask)是指在未来的某个时间点,执行相应的任务,本文为大家整理了三种常见的实现方法,感兴趣的小伙伴可以参考一下... 目录1.前言2.Redis如何实现延迟任务3.代码实现3.1. 过期键通知事件实现3.2. 使用ZSet实现延迟任务3.3

C语言函数递归实际应用举例详解

《C语言函数递归实际应用举例详解》程序调用自身的编程技巧称为递归,递归做为一种算法在程序设计语言中广泛应用,:本文主要介绍C语言函数递归实际应用举例的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录前言一、递归的概念与思想二、递归的限制条件 三、递归的实际应用举例(一)求 n 的阶乘(二)顺序打印

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

go中空接口的具体使用

《go中空接口的具体使用》空接口是一种特殊的接口类型,它不包含任何方法,本文主要介绍了go中空接口的具体使用,具有一定的参考价值,感兴趣的可以了解一下... 目录接口-空接口1. 什么是空接口?2. 如何使用空接口?第一,第二,第三,3. 空接口几个要注意的坑坑1:坑2:坑3:接口-空接口1. 什么是空接

Python中随机休眠技术原理与应用详解

《Python中随机休眠技术原理与应用详解》在编程中,让程序暂停执行特定时间是常见需求,当需要引入不确定性时,随机休眠就成为关键技巧,下面我们就来看看Python中随机休眠技术的具体实现与应用吧... 目录引言一、实现原理与基础方法1.1 核心函数解析1.2 基础实现模板1.3 整数版实现二、典型应用场景2

Python Dash框架在数据可视化仪表板中的应用与实践记录

《PythonDash框架在数据可视化仪表板中的应用与实践记录》Python的PlotlyDash库提供了一种简便且强大的方式来构建和展示互动式数据仪表板,本篇文章将深入探讨如何使用Dash设计一... 目录python Dash框架在数据可视化仪表板中的应用与实践1. 什么是Plotly Dash?1.1

Android Kotlin 高阶函数详解及其在协程中的应用小结

《AndroidKotlin高阶函数详解及其在协程中的应用小结》高阶函数是Kotlin中的一个重要特性,它能够将函数作为一等公民(First-ClassCitizen),使得代码更加简洁、灵活和可... 目录1. 引言2. 什么是高阶函数?3. 高阶函数的基础用法3.1 传递函数作为参数3.2 Lambda

C语言实现两个变量值交换的三种方式

《C语言实现两个变量值交换的三种方式》两个变量值的交换是编程中最常见的问题之一,以下将介绍三种变量的交换方式,其中第一种方式是最常用也是最实用的,后两种方式一般只在特殊限制下使用,需要的朋友可以参考下... 目录1.使用临时变量(推荐)2.相加和相减的方式(值较大时可能丢失数据)3.按位异或运算1.使用临时

Java中&和&&以及|和||的区别、应用场景和代码示例

《Java中&和&&以及|和||的区别、应用场景和代码示例》:本文主要介绍Java中的逻辑运算符&、&&、|和||的区别,包括它们在布尔和整数类型上的应用,文中通过代码介绍的非常详细,需要的朋友可... 目录前言1. & 和 &&代码示例2. | 和 ||代码示例3. 为什么要使用 & 和 | 而不是总是使

Python循环缓冲区的应用详解

《Python循环缓冲区的应用详解》循环缓冲区是一个线性缓冲区,逻辑上被视为一个循环的结构,本文主要为大家介绍了Python中循环缓冲区的相关应用,有兴趣的小伙伴可以了解一下... 目录什么是循环缓冲区循环缓冲区的结构python中的循环缓冲区实现运行循环缓冲区循环缓冲区的优势应用案例Python中的实现库