首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala、Cake模式和MacWire

Scala、Cake模式和MacWire
EN

Stack Overflow用户
提问于 2013-12-28 16:45:49
回答 1查看 1.3K关注 0票数 0

我使用蛋糕模式实现了一个电子邮件服务。下面是EmailComponent,它提供了电子邮件正文样式的功能:

代码语言:javascript
复制
trait EmailComponent {
  def body: Body

  trait Body {
    def style(content Html): Html
  }
}

trait DefaultEmailComponent extends EmailComponent {
  def body = new DefaultBody

  class DefaultBody extends Body {
    views.html.email(content)
  }
}

..。下面是使用EmailServiceComponent实现电子邮件服务的EmailComponent

代码语言:javascript
复制
trait EmailServiceComponent {
  def emailService: EmailService

  trait EmailService {
    def sendEmail(from: String, recipients: Seq[String], subject: String, content: Html)
  }
}

trait DefaultEmailServiceComponent extends EmailServiceComponent {
  this: EmailComponent =>

  def emailService = new DefaultEmailService

  class DefaultEmailService extends EmailService {
    def sendEmail(from: String, recipients: Seq[String], subject: String, content: Html) {
      val htmlBody = body.style(content)
      EmailHelper.sendEmail(from, recipients, Some(subject), (None, Some(htmlBody)))
    }
  }

上面的代码很好..。但当我看到MacWire时,我正在网上冲浪。我到处阅读一些文档,发现很有趣,但老实说,我还没有完全理解如何使用它,以及它是如何工作的。尽管如此,我如何才能用MacWire重新实现上面的示例呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-28 21:37:41

有几件事需要考虑:

  1. 一个很大的区别是,示例中的蛋糕模式使用继承/类组合来满足依赖关系并构建具体实例,而依赖注入则主要使用委托。这取决于您决定您希望这些类有多紧密耦合。
  2. 在使用在其他特征中定义的特征时,MacWire有连接的限制。因此,您的Default...实现必须超出它们的父特性。
  3. 乍一看,MacWire似乎无法解决一个特性的具体实现(与Guice不同,Guice是一个非常完善的依赖注入框架,您可以在那里使用绑定和注释)。这意味着您必须使用wire[DefaultEmailService]而不是wire[EmailService]
  4. 在MacWire中不支持循环依赖。在上面的例子中,您无论如何都没有它们: EmailServiceComponent依赖于EmailService,而后者又依赖于EmailComponent。

因此,使用MacWire,您的代码将只是使用其他类的类,如

代码语言:javascript
复制
class DefaultEmailComponent extends EmailComponent { ... }
class DefaultEmailService(emailComponent: EmailComponent) extends EmailService { ... }
trait EmailServiceComponent {
    def emailService: EmailService
}
class DefaultEmailServiceComponent(val emailService: EmailService) 
                                              extends EmailServiceComponent { ... }

lazy val emailC: EmailComponent = wire[DefaultEmailComponent]
lazy val emailSvc: EmailService = wire[DefaultEmailService]
lazy val emailSvcC: EmailServiceComponent = wire[DefaultEmailServiceComponent]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20816901

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档