2010-10-21 47 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