Q
設計模式和斯卡拉
9
A
回答
6
類似這樣的清單已經被整理過了。見https://wiki.scala-lang.org/display/SYGN/Design+Patterns
7
讓我們先從「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是構建在哪裏繼承並不真正適合類常用功能的一種方法。
1
相關問題
- 1. 模式在斯卡拉
- 2. 斯卡拉工廠模式
- 3. case類,模式匹配和斯卡拉
- 4. 斯卡拉功能API設計
- 5. 斯卡拉模塊
- 6. 斯卡拉:隱式
- 7. 斯卡拉填充模板的方式?
- 8. 斯卡拉子類模式匹配
- 9. 模式匹配 - 火花斯卡拉RDD
- 10. 使用模式在斯卡拉
- 11. 模式匹配或isInstanceOf斯卡拉
- 12. 斯卡拉如何通過模式
- 13. 模式匹配的斯卡拉`class`
- 14. &&和||在斯卡拉
- 15. PySpark和斯卡拉
- 16. 文檔計數/斯卡拉
- 17. 斯卡拉計數變量
- 18. 關於分佈式系統設計的問題 - 斯卡拉
- 19. 斯卡拉重現設置和日誌
- 20. 斯卡拉誤差建模
- 21. 獲取斯卡拉模板
- 22. 斯卡拉隱式類型轉換和==
- 23. 斯卡拉式擦除?
- 24. 斯卡拉方式/成語
- 25. 斯卡拉玩形式
- 26. 斯卡拉在斯卡拉類
- 27. 斯卡拉和廚師 - 最近的斯卡拉包
- 28. 斯卡拉推導/循環和類型化的模式
- 29. 斯卡拉模式匹配字符串和國際
- 30. Emacs的斯卡拉模式換行符和縮進怪事
意識到它太晚了,但這真的應該是社區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