设计模式和斯卡拉
答
让我们先从“Singleton模式”:
object SomeSingleton //That's it
我会还提出“使用 - 功能 - 的 - 高阶模式”。 而不是e。 G。通过自己迭代集合,您可以为类提供的方法提供函数。
Scala里,你基本上说,你打算做什么:
//declare some example class
case class Person(name: String, age: Int)
//create some example persons
val persons = List(Person("Joe", 42), Person("Jane", 30), Person("Alice", 14), Person("Bob", 12))
//"Are there any persons in this List, which are older than 18?"
persons.exists(_.age > 18)
// => Boolean = true
//"Is every person's name longer than 4 characters?"
persons.forall(_.name.length > 4)
// => Boolean = false
//"I need a List of only the adult persons!"
persons.filter(_.age >= 18)
// => List[Person] = List(Person(Joe,42), Person(Jane,30))
//"Actually I need both, a list with the adults and a list of the minors!"
persons.partition(_.age >= 18)
// => (List[Person], List[Person]) = (List(Person(Joe,42), Person(Jane,30)),List(Person(Alice,14), Person(Bob,12)))
//"A List with the names, please!"
persons.map(_.name)
// => List[String] = List(Joe, Jane, Alice, Bob)
//"I would like to know how old all persons are all together!"
persons.foldLeft(0)(_ + _.age)
// => Int = 98
在Java中这样做将意味着触摸收集自己的元素和混合与流量控制代码的应用程序逻辑。
More information关于Collection类。
这个漂亮EPFL paper有关弃用Observer模式可能会感兴趣了。
Typeclasses是构建在哪里继承并不真正适合类常用功能的一种方法。
答
意识到它太晚了,但这真的应该是社区wiki – 2010-10-22 02:47:31
@Dave同意,我不认为这是一个SO法律问题。但是,我很感兴趣看到答案,我希望它继续! – JAL 2010-10-22 04:47:19
您可能还想链接到[此问题](http://stackoverflow.com/questions/5566708/design-patterns-for-static-type-checking)。 – ziggystar 2011-05-05 07:30:34