8

मेरा विकास रोबोट पैर बाध्यकारी समस्या का व्यापक उपयोग करता है। मुझे how to solve itPrivateModule गुइस में पता है, लेकिन यह स्पष्ट नहीं है कि यह स्कैला के केक पैटर्न के साथ कैसे किया जाएगा।रोबोट पैरों को लागू करने के लिए मैं स्कैला के केक पैटर्न का उपयोग कैसे कर सकता हूं?

क्या कोई यह समझा सकता है कि यह कैसे किया जाएगा, आदर्श रूप से blog post के अंत में जोनास बोनर के कॉफी उदाहरण के आधार पर एक ठोस उदाहरण के साथ? शायद एक गर्म के साथ जो बाएं और दाएं किनारों के लिए कॉन्फ़िगर किया जा सकता है, एक अभिविन्यास के साथ इंजेक्शन और 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 
संबंधित मुद्दे

 संबंधित मुद्दे