1 Feb 2010 01:34
Swapping notes on the "Implicit Builder" pattern
Inspired by the 2.8 collections design, Ive been doing some
experimentation with an "Implicit Builder" design pattern.
The basics of the pattern are summarized (in "bare-bones" form) in the
code below. This pattern allows abstract or generic code to
instantiate concrete subtypes of which it has no knowledge, by means
of an implicit builder parameter. Ultimately, the default concrete
types are still fixed at compile time, but control over them becomes
clustered in convenient place (eg in the Builder's companion object).
//library code
abstract class Container1[T] {
def aTransform(implicit builder: Builder[T]): Container2[T] = builder(this)
}
class StringContainer1 extends Container1[String]
class IntContainer1 extends Container1[Int]
abstract class Container2[T]
class StringContainer2 extends Container2[String]
class IntContainer2 extends Container2[Int]
trait Builder[T] {
def apply(c: Container1[T]): Container2[T]
}
object Builder {
implicit val stringBuilder = new Builder[String] {def apply(c:
Container1[String]) = new StringContainer2 }
implicit val intBuilder = new Builder[Int] {def apply(c:
Container1[Int]) = new IntContainer2 }
(Continue reading)
RSS Feed