Created
February 21, 2012 06:04
-
-
Save kencoba/1874123 to your computer and use it in GitHub Desktop.
FactoryMethod pattern (Design Patterns in Scala)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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