Scalaz(16)- Monad:依赖注入-Dependency Injection By Reader Monad

简介:

在上一篇讨论里我们简单的介绍了一下Cake Pattern和Reader Monad是如何实现依赖注入的。主要还是从方法上示范了如何用Cake Pattern和Reader在编程过程中解析依赖和注入依赖。考虑到依赖注入模式在编程中的重要性和普遍性,觉着还需要再讨论的深入一些,使依赖注入模式在FP领域里能从理论走向实际。既然我们正在scalaz的介绍系列里,所以这篇我们就着重示范Reader Monad的依赖注入方法。

  再说明一下依赖注入:我们说过在团队协作开发里能够实现软件模块的各自独立开发,原理首先是实现软件模块之间的松散耦合(decoupling)。对依赖注入的学术定义如下:Dependency Inversion Principle

1、上层模块不应该依赖下层模块,反之亦然。它们之间不应该有直接的代码引用。它们应该都依赖一个抽象的中间层,也就是共享接口(interface)。

2、抽象层不应该依赖实现细节,而细节实现则必须依赖抽象层。大家都按照共享的抽象层进行实现细节编程。

这两条足够解释何为软件模块松散耦合以及具体编码的要求了。这样来说不仅在团队协同开发,即使在个人独立开发环境下依赖注入模式也能发挥良好的作用。一是可以按需要把软件切分成功能模块独立编程。通过依赖注入模式,当下层模块进行了调整后是不会影响上层模块的;上层模块可以随时连接不同的下层功能模块实现不同的功能,比如连接一些测试环境实现上层模块的独立测试。

下面我们还是取用上期的示范例子,由简入深,逐步说明Reader依赖注入的原理、组合、结构设计:

还说那个咖啡机例子:包括了一个开关设备、咖啡感应器;如果感应到壶里有咖啡的话,按下开关咖啡机可以开启加热。

下面是功能抽象描述,它们是按照开发条件和环境需要进行具体细分的。细分程度要确保每项功能都可以独立完成编程。


trait OnOffDevice {
    def on: Unit
    def off: Unit
  }
  trait SensorDevice {
    def isCoffeePresent: Boolean
  }

这就是一个抽象层。所有开发人员都必须按照这层的功能描述来编程,所谓编程细节依赖与抽象层要求。

我们现在就可以不用理会以上功能是否已经实现,立即进入上层模块的功能组合了。我们只需要申明依赖项目,先从最简单的开始,假如我现在只需要引用OnOffDevice一项依赖的话,可以在伴生对象(companion object)这样申明操作Reader(primitive reader):


1 object OnOffDevice {
2   def on: Reader[OnOffDevice, String] = Reader(_.on)
3   def off:  Reader[OnOffDevice, String] = Reader(_.off)
4 }

由于只有一个依赖,我们可以直接申明功能Reader,把on,off两个函数变成Primitive Reader。假如我们需要函数运算结果的话,只要注入OnOffDevice实例。由于Reader是个Monad,我们可以用map这样写:


1 object OnOffDevice {
2   def onOffDevice: Reader[OnOffDevice,OnOffDevice] = Reader(identity)
3   def on: Reader[OnOffDevice,String] = onOffDevice map { _.on }
4   def off: Reader[OnOffDevice,String] = onOffDevice map { _.off }
5 }

我们用identity构建了一个基础(primitive)Reader,然后以这个基础Reader用map组合成我们需要的功能函数Reader。现在的on,off函数款式(signature)和前面的定义是一样的。现在我们可以实现这些Reader功能:


object OnOffService {
    def on = for {
        ison <- OnOffDevice.on
    } yield ison
    def off = for {
        isoff <- OnOffDevice.off
    } yield isoff
}

我们抽象化了OnOffDevice,不需要实现依赖项目就可以直接使用这些Reader功能函数:


1 ef trigger = OnOffService.on      //> trigger: => scalaz.Kleisli[scalaz.Id.Id,OnOffDevice,String]

假如现在实现了OnOffDevice实例:


1 class OnOffDeviceImpl extends OnOffDevice {
2     def on = "MockDevice.On"
3     def off = "MockDevice.Off"
4 }

我们可以在最终运行中注入实现的依赖实例来获取最终结果:


1 object MockOnOffDevice extends OnOffDeviceImpl
2 def trigger = OnOffService.on                     //> trigger: => scalaz.Kleisli[scalaz.Id.Id,Exercises.reader1.OnOffDevice,String
3                                                   //| ]
4 val result = trigger(MockOnOffDevice)             //> result  : scalaz.Id.Id[String] = SomeDevice.On
5 result === "SomeDevice.On"                        //> res0: Boolean = true

我们看到,对运算结果注入依赖实例后就能得出具体的运算值。

那如果我们需要两项依赖呢?


trait OnOffDevice {
    def on: String
    def off: String
}
trait SensorDevice {
    def isCoffeePresent: Boolean
}

我们可以把两个依赖组成一个更大的功能,一个更高一层的依赖:



rait Device { //高层组合依赖
  def onOffDevice: OnOffDevice     //具体依赖
  def sensorDevice: SensorDevice   //具体依赖
}
object Device {
  val device = Reader[Device,Device](identity)
  val onOffDevice = device map {_.onOffDevice}
  val sensorDevice = device map {_.sensorDevice}
}

所有Reader的注入依赖现在变成Device类型了。依赖的功能Reader变成这样:


object OnOffDevice {
import Device.onOffDevice
    def on: Reader[Device,String] = onOffDevice map { _.on }
    def off: Reader[Device,String] = onOffDevice map { _.off }
}
object SensorDevice {
import Device.sensorDevice
  def isCoffeePresent: Reader[Device,Boolean] = sensorDevice map { _.isCoffeePresent }
}

我们看到原来的Reader实现细节编码是不需要改变的,如OnOffService。
假设我们获得了下面的功能实现程序:


class OnOffDeviceImpl extends OnOffDevice {
    def on = "SomeDevice.On"
    def off = "SomeDevice.Off"
}
class SensorDeviceImpl extends SensorDevice {
    def isCoffeePresent = true
}

由于这次的依赖注入是Device类型的,所以我们需要获取Device实例用来注入到结果Reader:


object MockOnOffDevice extends OnOffDeviceImpl
object MockSensorDevice extends SensorDeviceImpl
trait DeviceImpl extends Device {
    def onOffDevice = new OnOffDevice {
        def on = MockOnOffDevice.on
        def off = MockOnOffDevice.off
    }
    def sensorDevice = new SensorDevice {
        def isCoffeePresent = MockSensorDevice.isCoffeePresent
    }
}

现在这个DeviceImpl是一个Device实例,我们可以把它注入到Reader得出运算结果,还是先运行上面的例子:


1 object MockDevice extends Device with DeviceImpl
2 def trigger = OnOffService.on                     //> trigger: => scalaz.Kleisli[scalaz.Id.Id,Exercises.reader2.Device,String]
3 val result = trigger(MockDevice)                  //> result  : scalaz.Id.Id[String] = SomeDevice.On

这次是用Device实例注入得出结果的。

我们还可以把依赖项目独立分别定义,这样可以更灵活的组合Device:


trait OnOffComponent {
    def onOffDevice: OnOffDevice
}
trait SensorComponent {
    def sensorDevice: SensorDevice
}
trait Device extends OnOffComponent with SensorComponent

这样我们可以把两个依赖分开来格式化后组合成Device实例,因为我们的注入依赖现在是Device类型的了:


object MockOnOffDevice extends OnOffDeviceImpl
object MockSensorDevice extends SensorDeviceImpl
trait OnOffFunctions extends OnOffComponent {
    def onOffDevice = MockOnOffDevice
}
trait SensorFunctions extends SensorComponent {
  def sensorDevice = MockSensorDevice
}

完成了Device实例的组合后可以通过注入Device实例来得取运算结果:


object MockDevice extends Device with OnOffFunctions with SensorFunctions
def trigger =
  if (SensorService.isCoffeePresent(MockDevice))
     OnOffService.on(MockDevice)
  else
     OnOffService.off(MockDevice)                 //> trigger: => scalaz.Id.Id[String]
trigger                                           //> res0: scalaz.Id.Id[String] = SomeDevice.On

如果换另一个版本的SensorDevice实现:


1 class SensorDeviceImpl extends SensorDevice {
2     def isCoffeePresent = false
3 }

重新运行:


object MockDevice extends Device with OnOffFunctions with SensorFunctions
def trigger =
  if (SensorService.isCoffeePresent(MockDevice))
     OnOffService.on(MockDevice)
  else
     OnOffService.off(MockDevice)                 //> trigger: => scalaz.Id.Id[String]
trigger                                           //> res0: scalaz.Id.Id[String] = SomeDevice.Off

正确反应了新的运算结果。

从以上的示范中我们看到了依赖的层次结构以及Reader搭配。我们可以用多层结构来精简基础Reader。但多层式的依赖结构统一了注入依赖类型,最后注入时就无法拆分依赖类型,又会弱化依赖的组合灵活性。所以在组织依赖时应该注意确定在自己的程序中将会使用到所有依赖。这样调用统一的一种注入类型就足够了。

下面再增添多一个依赖:增加一个电源制式检测功能,只有US制式的电源才能启动咖啡机。现在全部功能的抽象描述如下:


trait OnOffDevice {
    def on: String
    def off: String
}
trait SensorDevice {
    def isCoffeePresent: Boolean
}
trait PowerConfig {
  def getPowerVolts(country: String): Int
  def isUSStandard(volt: Int): Boolean
}

我们再试试增加多一层结构:


trait Device extends OnOffComponent with SensorComponent
trait DeviceComponent {
    def onOffDevice: OnOffDevice
    def sensorDevice: SensorDevice
}
trait PowerComponent {
    def powerConfig: PowerConfig
}
trait Appliance extends DeviceComponent with PowerComponent
object Appliance {
  val appliance = Reader[Appliance,Appliance](identity)
  val onOffDevice = appliance map {_.onOffDevice}
  val sensorDevice = appliance map {_.sensorDevice}
  val powerConfig = appliance map {_.powerConfig}
}

Appliance是更高层依赖。

下面还是保留了原来的Reader实现编码不变,除了import:


object OnOffDevice {
import Appliance.onOffDevice
    def on: Reader[Appliance,String] = onOffDevice map { _.on }
    def off: Reader[Appliance,String] = onOffDevice map { _.off }
}
object SensorDevice {
import Appliance.sensorDevice
  def isCoffeePresent: Reader[Appliance,Boolean] = sensorDevice map { _.isCoffeePresent }
}
object PowerConfig {
import Appliance.powerConfig
    def getPowerVolts(country: String) = powerConfig map {_.getPowerVolts(country)}
    def isUSStandard(volts: Int) = powerConfig map {_.isUSStandard(volts)}
}

现在注入依赖的类型变成了Appliance。原来Reader功能实现代码还是不用改变:


object OnOffService {
    def on = for {
        ison <- OnOffDevice.on
    } yield ison
    def off = for {
        isoff <- OnOffDevice.off
    } yield isoff
}
object SensorService {
    def isCoffeePresent = for {
        hasCoffee <- SensorDevice.isCoffeePresent
    } yield hasCoffee
}
object PowerService {
    def isUSStandard(country: String) = for {
        is110v <- PowerConfig.getPowerVolts(country)
        isUSS <- PowerConfig.isUSStandard(is110v)
    } yield isUSS
}

假如增加了新功能实现程序:


class OnOffDeviceImpl extends OnOffDevice {
    def on = "SomeDevice.On"
    def off = "SomeDevice.Off"
}
class SensorDeviceImpl extends SensorDevice {
    def isCoffeePresent = true
}
class PowerConfigImpl extends PowerConfig {
    def getPowerVolts(country: String) = country match {
        case "USA" => 110
        case "UK" => 220
        case "HK" => 220
        case "CHN" => 110
        case _  => 0
    }
    def isUSStandard(volts: Int) = volts === 110
}

同样,需要把这些实例转成Appliance类型: 


object MockOnOffDevice extends OnOffDeviceImpl
object MockSensorDevice extends SensorDeviceImpl
object MockPowerConfig extends PowerConfigImpl
trait OnOffFunctions extends OnOffComponent {
    def onOffDevice = MockOnOffDevice
}
trait SensorFunctions extends SensorComponent {
  def sensorDevice = MockSensorDevice
}
trait DeviceFunctions extends DeviceComponent  {
    def onOffDevice = MockOnOffDevice
  def sensorDevice = MockSensorDevice
}
trait PowerFunctions extends PowerComponent {
    def powerConfig = MockPowerConfig
}

再直接进行Appliance实例组合:


1 object MockAppliance extends Appliance with DeviceFunctions with PowerFunctions


def trigger =
  if ((PowerService.isUSStandard("CHN")(MockAppliance))
      && (SensorService.isCoffeePresent(MockAppliance)))
       OnOffService.on(MockAppliance)
   else
     OnOffService.off(MockAppliance)              //> trigger: => scalaz.Id.Id[String]
trigger                                           //> res0: scalaz.Id.Id[String] = SomeDevice.On

下面是这段程序的源代码,提供给大家作为参考:


package Exercises
import scalaz._
import Scalaz._
object reader3 {
trait OnOffDevice {
    def on: String
    def off: String
}
trait SensorDevice {
    def isCoffeePresent: Boolean
}
trait PowerConfig {
  def getPowerVolts(country: String): Int
  def isUSStandard(volt: Int): Boolean
}

trait OnOffComponent {
    def onOffDevice: OnOffDevice
}
trait SensorComponent {
    def sensorDevice: SensorDevice
}
trait Device extends OnOffComponent with SensorComponent
trait DeviceComponent {
    def onOffDevice: OnOffDevice
    def sensorDevice: SensorDevice
}
trait PowerComponent {
    def powerConfig: PowerConfig
}
trait Appliance extends DeviceComponent with PowerComponent
object Appliance {
  val appliance = Reader[Appliance,Appliance](identity)
  val onOffDevice = appliance map {_.onOffDevice}
  val sensorDevice = appliance map {_.sensorDevice}
  val powerConfig = appliance map {_.powerConfig}
}
object OnOffDevice {
import Appliance.onOffDevice
    def on: Reader[Appliance,String] = onOffDevice map { _.on }
    def off: Reader[Appliance,String] = onOffDevice map { _.off }
}
object SensorDevice {
import Appliance.sensorDevice
  def isCoffeePresent: Reader[Appliance,Boolean] = sensorDevice map { _.isCoffeePresent }
}
object PowerConfig {
import Appliance.powerConfig
    def getPowerVolts(country: String) = powerConfig map {_.getPowerVolts(country)}
    def isUSStandard(volts: Int) = powerConfig map {_.isUSStandard(volts)}
}
object OnOffService {
    def on = for {
        ison <- OnOffDevice.on
    } yield ison
    def off = for {
        isoff <- OnOffDevice.off
    } yield isoff
}
object SensorService {
    def isCoffeePresent = for {
        hasCoffee <- SensorDevice.isCoffeePresent
    } yield hasCoffee
}
object PowerService {
    def isUSStandard(country: String) = for {
        is110v <- PowerConfig.getPowerVolts(country)
        isUSS <- PowerConfig.isUSStandard(is110v)
    } yield isUSS
}
class OnOffDeviceImpl extends OnOffDevice {
    def on = "SomeDevice.On"
    def off = "SomeDevice.Off"
}
class SensorDeviceImpl extends SensorDevice {
    def isCoffeePresent = true
}
class PowerConfigImpl extends PowerConfig {
    def getPowerVolts(country: String) = country match {
        case "USA" => 110
        case "UK" => 220
        case "HK" => 220
        case "CHN" => 110
        case _  => 0
    }
    def isUSStandard(volts: Int) = volts === 110
}
object MockOnOffDevice extends OnOffDeviceImpl
object MockSensorDevice extends SensorDeviceImpl
object MockPowerConfig extends PowerConfigImpl
trait OnOffFunctions extends OnOffComponent {
    def onOffDevice = MockOnOffDevice
}
trait SensorFunctions extends SensorComponent {
  def sensorDevice = MockSensorDevice
}
trait DeviceFunctions extends DeviceComponent  {
    def onOffDevice = MockOnOffDevice
  def sensorDevice = MockSensorDevice
}
trait PowerFunctions extends PowerComponent {
    def powerConfig = MockPowerConfig
}
object MockAppliance extends Appliance with DeviceFunctions with PowerFunctions
def trigger =
  if ((PowerService.isUSStandard("CHN")(MockAppliance))
      && (SensorService.isCoffeePresent(MockAppliance)))
       OnOffService.on(MockAppliance)
   else
     OnOffService.off(MockAppliance)              //> trigger: => scalaz.Id.Id[String]
trigger                                           //> res0: scalaz.Id.Id[String] = SomeDevice.On
}

相关文章
|
编解码 数据安全/隐私保护 开发者
uniapp打包的ipa上架到appstore的傻瓜式教程
uniapp打包的ipa上架到appstore的傻瓜式教程
351 0
|
3月前
|
人工智能 自然语言处理 搜索推荐
GEO优化怎么选词?国内大模型能用哪些数据作依据
本文破解GEO选词困局:指出问题不在词多寡,而在缺乏数据支撑。详解国内大模型检索链路中“词”的三层粒度(入口/答案/限定),结合六类可信数据源与六大筛选维度,提供可落地的词表构建、测试、打分与复测全流程,助内容真正被AI引用。
246 0
|
4月前
|
人工智能 运维 IDE
零成本AI编程实战|Qoder CN免费社区版全解,额度规则、多端部署与CLI实操命令完整指南
AI赋能研发已经成为软件开发领域的主流趋势,AI编码助手可以极大降低重复编码工作量,提升学习与开发效率。但市面上大量高质量AI编程工具普遍采用订阅付费模式,对于编程学生、业余爱好者、初级开发者来说,长期订阅会带来不小的经济负担,抬高了AI编程的入门门槛。为了普惠广大基层开发群体,降低AI编程落地门槛,原通义灵码完成品牌迭代升级,正式更名为Qoder CN,并且推出永久可用的免费社区版本。该版本配套独立Credits额度体系,普通用户不需要付费订阅,就可以使用专业级AI编码智能体能力,覆盖代码学习、脚本编写、小型项目开发、代码调试等轻量化开发场景。
1350 0
|
7月前
|
SQL 运维 监控
生产环境改了个配置,半小时后业务挂了——变更管理到底管什么
统计过去半年的P1/P2故障,接近4成是配置变更引发的。本文从一次连接池参数误改导致的生产事故出发,拆解最小可用的变更管理4个动作——分级、记录、通知、关联,不搞ITIL全套流程,先让变更可追溯、可关联、出了事能3分钟定位。
1046 1
生产环境改了个配置,半小时后业务挂了——变更管理到底管什么
|
12月前
|
存储 机器学习/深度学习 安全
阿里云服务器租用价格:2核4G与4核8G配置按量、包年包月收费标准与活动价格参考
2核4G、4核8G配置一般适用于中小型网站、企业网站应用、批量计算、Web前端服务器、机器学习推理等场景,因此,多为个人和普通企业级用户比较喜欢购买这种配置。2核4G配置按年购买u1实例2核4G5M带宽仅需199元,4核8G配置按年购买u2a实例4核8G目前活动价格为898.20元/1年起。本文为大家整理了目前核4G与4核8G配置按量、包年包月收费标准与活动价格,以供对比和选择参考。
2865 4
|
12月前
|
人工智能 文字识别 自然语言处理
金融行业RPA案例大全:银行_证券_保险全场景落地实践(附数据)
凌晨两点的金融城灯火通明,RPA“数字员工”正悄然变革行业。从银行对账到证券清算、保险理赔,重复工作被高效替代。实在智能的实在Agent作为第三代RPA,融合AI与大模型,实现智能决策与自主学习,助力金融机构降本增效,推动服务迈向智能化。
905 2
|
安全 BI API
WhatsApp的名词都是什么意思?从个人账号到商业平台全解析
WhatsApp、WhatsApp Business API、WhatsApp Business 、Meta 蓝标、这些分别都是什么意思,有哪些区别?
3813 0
|
网络虚拟化 网络架构
三层交换机的详细配置步骤
三层交换机的详细配置步骤 1、三层交换机 三层交换机就是具有部分路由器功能的交换机,工作在OSI网络标准模型的第三层:网络层。三层交换机的最重要目的是加快大型局域网内部的数据交换,所具有的路由功能也是为这目的服务的,能够做到一次路由,多次转发。
4504 0
|
JavaScript Java 测试技术
基于Java+SpringBoot+Vue实现的车辆充电桩系统设计与实现(系统源码+文档+部署讲解等)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!