设计模式和Scala

ade*_*rsq 13 design-patterns scala

我正在编写这个问题来维护与Scala相关的设计模式的注册,标准模式或仅来自这种语言.

相关问题:

感谢所有贡献者

soc*_*soc 7

让我们从"单身模式"开始:

object SomeSingleton //That's it
Run Code Online (Sandbox Code Playgroud)

我还会提出"使用更高阶模式的函数".您可以为类提供的方法提供函数,而不是例如自己迭代集合.

在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
Run Code Online (Sandbox Code Playgroud)

在Java中执行此操作意味着自己触摸集合的元素并将应用程序逻辑与流控制代码混合在一起.

有关 Collection类的更多信息.


这篇关于弃用观察者模式的EPFL论文也可能引起人们的兴趣.


类型类是构造类的共同特征的一种方法,其中继承不适合.

  • 令人遗憾的是,"级别"或通用编程语言是这样的......构造......必须被引出并被称为"设计模式"(好像它们应该保证任何额外的负担:-) (2认同)
  • "使用 - 更高阶模式的模式"是GoF的策略 (2认同)

Syn*_*sso 6

这样的列表已经整理好了.请参阅https://wiki.scala-lang.org/display/SYGN/Design+Patterns