Skip to content

Instantly share code, notes, and snippets.

@kencoba
Created February 21, 2012 06:04
Show Gist options
  • Save kencoba/1874123 to your computer and use it in GitHub Desktop.
Save kencoba/1874123 to your computer and use it in GitHub Desktop.
FactoryMethod pattern (Design Patterns in Scala)
// http://blog.designrecipe.jp/2011/01/03/factory-method-strategy/
abstract class ListPrinter {
def printList(list: List[String]) {
val comparator = createComparator
list.sortWith(comparator).foreach(println)
}
protected def createComparator: (String, String) => Boolean
}
class DictionaryOrderListPrinter extends ListPrinter {
override protected def createComparator: (String, String) => Boolean =
(s1, s2) => s1 < s2
}
class LengthOrderListPrinter extends ListPrinter {
override protected def createComparator: (String, String) => Boolean =
(s1, s2) => s1.size < s2.size
}
object FactoryMethodPatternExampleWiki {
def main(args: Array[String]) = {
val strs = List("apple", "plum", "pineapple")
println("alphabetical sort:")
(new DictionaryOrderListPrinter).printList(strs)
println("length ordered sort:")
(new LengthOrderListPrinter).printList(strs)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment