8

Phát triển của tôi sử dụng rộng rãi vấn đề ràng buộc chân robot. Tôi biết how to solve it với PrivateModule ở Guice, nhưng không rõ điều này sẽ được thực hiện như thế nào với mẫu bánh của Scala.Làm thế nào tôi có thể sử dụng mẫu bánh của Scala để thực hiện chân robot?

Ai đó có thể giải thích cách thực hiện điều này, lý tưởng nhất là với ví dụ cụ thể dựa trên ví dụ về cà phê của Jonas Boner ở cuối số blog post? Có lẽ với một ấm hơn có thể được cấu hình cho bên trái và bên phải, tiêm với một định hướng và một def isRightSide?

Trả lời

3

Mẫu bánh không giải quyết được sự cố này ở dạng ban đầu. Bạn có several choices cách giải quyết vấn đề đó. Giải pháp tôi thích là tạo mỗi "chân robot" bằng cách gọi hàm tạo của nó với tham số thích hợp - code cho thấy rằng tốt hơn, so với từ.

Tôi nghĩ câu trả lời trích dẫn trên là dễ đọc hơn, nhưng nếu bạn đã quen thuộc với Jonas' dụ, đây là cách bạn muốn làm cho cấu hình Warmer với định hướng:

// ======================= 
// 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 
Các vấn đề liên quan