8

내 발달은 로봇 다리 바인딩 문제를 광범위하게 사용합니다. Guice에서 how to solve itPrivateModule으로 알고 있습니다. 그러나 이것이 Scala의 케이크 패턴으로 어떻게 수행되는지는 명확하지 않습니다.Scala의 케이크 패턴을 사용하여 로봇 다리를 구현하는 방법은 무엇입니까?

누군가가 이것을 어떻게 완료 할 것인지 설명해 주실 수 있습니까? 예를 들어, blog post의 끝에 Jonas Boner의 커피 예제를 기반으로 한 구체적인 예가 이상적입니까? 어쩌면 왼쪽 및 오른쪽으로 구성 할 수있는 더 따뜻하고 오리엔테이션과 def isRightSide을 주입 했습니까?

답변

3

케이크 패턴은 원래 형태로이 문제를 해결하지 못합니다. 그걸 처리하는 방법은 several choices입니다. 내가 선호하는 솔루션은 적절한 매개 변수를 사용하여 생성자를 호출하여 각 "로봇 다리"를 만드는 것입니다. code은 단어보다 더 나은 결과를 보여줍니다.

나는 위의 인용 된 응답을 더 읽을 생각하지만, 이미 조나스 '예에 익숙하다면, 여기 당신은 오리엔테이션과 비슷해 구성을 줄 방법은 다음과 같습니다

// ======================= 
// service interfaces 
trait OnOffDeviceComponent { 
    val onOff: OnOffDevice 
    trait OnOffDevice { 
    def on: Unit 
    def off: Unit 
    } 
} 
trait SensorDeviceComponent { 
    val sensor: SensorDevice 
    trait SensorDevice { 
    def isCoffeePresent: Boolean 
    } 
} 

// ======================= 
// service implementations 
trait OnOffDeviceComponentImpl extends OnOffDeviceComponent { 
    class Heater extends OnOffDevice { 
    def on = println("heater.on") 
    def off = println("heater.off") 
    } 
} 
trait SensorDeviceComponentImpl extends SensorDeviceComponent { 
    class PotSensor extends SensorDevice { 
    def isCoffeePresent = true 
    } 
} 
// ======================= 
// service declaring two dependencies that it wants injected 
trait WarmerComponentImpl { 
    this: SensorDeviceComponent with OnOffDeviceComponent => 

    // Note: Warmer's orientation is injected by constructor. 
    // In the original Cake some mixed-in val/def would be used 
    class Warmer(rightSide: Boolean) { 
    def isRightSide = rightSide 
    def trigger = { 
     if (sensor.isCoffeePresent) onOff.on 
     else onOff.off 
    } 
    } 
} 

// ======================= 
// instantiate the services in a module 
object ComponentRegistry extends 
    OnOffDeviceComponentImpl with 
    SensorDeviceComponentImpl with 
    WarmerComponentImpl { 

    val onOff = new Heater 
    val sensor = new PotSensor 
    // Note: now we need to parametrize each particular Warmer 
    // with its desired orientation 
    val leftWarmer = new Warmer(rightSide = false) 
    val rightWarmer = new Warmer(rightSide = true) 
} 

// ======================= 
val leftWarmer = ComponentRegistry.leftWarmer 
leftWarmer.trigger 
관련 문제