Cake Pattern ã®ç°¡åãªä¾ãæ¸ãã¦ãã
Cake Pattern ã®èª¬æ㯠Programming Scala ããããhttp://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di/ ã®æ¹ãåãããããã£ãã§ãã
ä¸å¿ãèªåãªãã«ç解ã§ããã¤ããã§ããã®ã§ãã¨ããããç°¡åãªä¾ãæ¸ãã¦ããã¾ãã
åºç¾ããã³ã³ãã¼ãã³ã㯠FooãBar ã®äºã¤ãBar ã Foo ã«ä¾åãã¦ããä¾ã§ãã
package sample01 trait FooComponent { val foo: Foo class Foo { def output(text: String) = println(text) } } trait BarComponent { self: FooComponent => val bar: Bar class Bar { def process(name: String) = foo.output("Hello %s world!".format(name)) } } object ComponentRegistry extends FooComponent with BarComponent { val foo = new Foo val bar = new Bar } object Main { def main(args: Array[String]) = ComponentRegistry.bar.process("Scala") }
å®è¡ãã㨠"Hello Scala world!" ã¨åºåããã¾ãã
ãã®ä¾ã®å ´åãã³ã³ãã¼ãã³ãæä¾å´ã¨å©ç¨å´ã¨ãåãtraitã使ç¨ãã¦ãã¾ãããã®ããããã¾ãã¡ç解ãã¥ãããããªã®ã§ãtrait ãåå²ãã¦ã¿ã¾ãã*1
package sample02 // ã³ã³ãã¼ãã³ãå©ç¨è ã«å ¬é trait Foo { def output(text: String): Unit } trait FooInstance { val foo: Foo } trait Bar { def process(name: String): Unit } trait BarInstance { val bar: Bar } // ã³ã³ãã¼ãã³ãã®å®è£ trait FooComponent { class FooImpl extends Foo { def output(text: String) = println(text) } } trait BarComponent { self: FooInstance => class BarImpl extends Bar { def process(name: String) = foo.output("Hello %s world!".format(name)) } } // ã³ã³ãã¼ãã³ããªãã¸ã㪠object ComponentRegistry extends FooInstance with FooComponent with BarInstance with BarComponent { val foo = new FooImpl val bar = new BarImpl } object Main { def main(args: Array[String]) = ComponentRegistry.bar.process("Scala") }
ãã®ä¾ã§ã¯ãBar ã³ã³ãã¼ãã³ã(ã®å®è£
ã¯ã©ã¹ã§ãã BarImpl)㯠FooInstance ãã¬ã¤ãã®ãã£ã¼ã«ã val foo: Foo ãåç
§ãã¦ãFoo ã³ã³ãã¼ãã³ããå©ç¨ãã¦ãã¾ãããã®ã¨ããBar ã³ã³ãã¼ãã³ã㯠Foo ã³ã³ãã¼ãã³ãã®å®è£
ã«ä¾åãããã¨ãªããã¾ã foo ã«ã¯æå¹ãªå¤ãè¨å®ããã¦ãããã¨ãåæã¨ãã¦å©ç¨ã§ãã¦ãã¾ããããã¯ãDI ã³ã³ããå©ç¨æã«ãä¾åã³ã³ãã¼ãã³ãããã£ã¼ã«ãã¨ãã¦åç
§ããã®ã¨ä¼¼ã¦ãããã¨æãã¾ãã
ã¾ããDI ã³ã³ããå©ç¨æã¯ãã³ã³ãããä¾åã³ã³ãã¼ãã³ãããã£ã¼ã«ãã«è¨å®ãã¦ããã¾ãããCake Pattern ã®å ´åã¯ãã¹ã¦ã®ã³ã³ãã¼ãã³ããä¿æãã ComponentRegistry ã§ãåãã£ã¼ã«ãã«ã³ã³ãã¼ãã³ããè¨å®ãã¾ããã¡ãªã¿ã«ããã£ã¼ã«ã㯠val ã¨ãã¦å®£è¨ããã¦ãããããè¨å®æ¼ããããå ´åã¯ã³ã³ãã¤ã«ã¨ã©ã¼ã¨ãªãã¾ããå®è¡ããã¨ãè¨å®æ¼ãã«æ°ä»ããã¨ããã®ã¯å¬ããç¹ã§ãã
Cake Pattern ãå©ç¨ããå ´åãDI ã³ã³ãããæä¾ããæ©è½ã®ããã¤ããè¨èªã®æ©è½ã§å®ç¾ãããã¨ãåºæ¥ã¾ãããã ãAOP ã§ãã£ããã¹ã³ã¼ãã®å¶å¾¡(ãªã¯ã¨ã¹ãã®ãã³ã«çæç)ã§ãã£ãã㯠DI ã³ã³ããã®æ¹ãæ±ããããã®ããªã¨æãã¾ãããã¾ã DI ã³ã³ãã㨠Cake Pattern ãä½µç¨ã§ããã¨ããè¯ãã®ããç¥ãã¾ããã
追è¨(2010/01/19)
ã¤ã³ã¿ãã§ã¼ã¹ã¨å®è£ ãåé¢ããã®ã¯ãhttp://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di/ ã®ä¸çªä¸ã«æ¸ãã¦ãã£ãã§ããããèªãã§ãã¾ããã§ãã(æ±
*1:è¤æ°ã®å®è£ ãããããã§ããªãã®ã§ãCake Pattern ãå®éã«ä½¿ç¨ããæã«ã¯ trait ãåå²ããå¿ è¦ã¯ç¡ãã¨æãã¾ãã