2010-10-21 60 views
9

我正在寫這個問題,以維護與Scala相關的設計模式,標準模式或只從這種語言註冊。設計模式和斯卡拉

相關問題:

感謝所有誰貢獻

+0

意識到它太晚了,但這真的應該是社區wiki – 2010-10-22 02:47:31

+0

@Dave同意,我不認爲這是一個SO法律問題。但是,我很感興趣看到答案,我希望它繼續! – JAL 2010-10-22 04:47:19

+0

您可能還想鏈接到[此問題](http://stackoverflow.com/questions/5566708/design-patterns-for-static-type-checking)。 – ziggystar 2011-05-05 07:30:34

回答

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是構建在哪裏繼承並不真正適合類常用功能的一種方法。

+2

很遺憾,「級」或通用編程語言是這樣的,這些......構造......必須被引出來並稱爲「設計模式」(好像他們應該承擔任何額外的負擔:-) – 2010-10-22 00:45:46

+2

「使用高階函數的模式」是GoF的策略 – Synesso 2010-10-22 00:57:13

+0

爲了使單例更具可測性,最好留下部分(如果不是滿的)在特質中實現。 //代碼 性狀SomeSingleton { DEF doSomething1 {} 懶惰VAL VAL1 } 對象SomeSingleton延伸SomeSingleton – Nick 2014-04-21 13:53:57