[英]Scala, Cake Pattern, and MacWire
我使用蛋糕模式實現了電子郵件服務。 下面是EmailComponent
,它提供了為電子郵件正文設置樣式的功能:
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
:
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重新實現上面的例子?
需要考慮的幾件事:
一個很大的區別是,示例中的cake模式使用繼承/類組合來滿足依賴關系並構建具體實例,而使用依賴注入則主要使用委托。 由您來決定您希望這些課程的緊密耦合程度。
在使用其他特征內定義的特征時,MacWire有限制接線。 因此,您的Default...
實現必須超出其父特征。
快速瀏覽一下,似乎MacWire無法解析特征的具體實現(與Guice不同,Guice是一個完善的Java依賴注入框架,您可以在其中使用綁定和注釋)。 這意味着您必須使用wire[DefaultEmailService]
而不是wire[EmailService]
。
在MacWire中不支持循環依賴。 在上面的例子中,你還沒有它們:EmailServiceComponent依賴於EmailService,而EmailService依賴於EmailComponent。
因此,對於MacWire,您的代碼只是使用其他類的類,比如
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.