9

在 C# 中,类和接口可以有event

public class Foo
{
    public event Action SomethingHappened;

    public void DoSomething()
    {
        // yes, i'm aware of the potential NRE
        this.SomethingHappened();
    }
}

这有助于使用最少的样板代码实现基于推送的通知,并启用多订阅者模型,以便许多观察者可以监听事件:

var foo = new Foo();
foo.SomethingHappened += () => Console.WriteLine("Yay!");
foo.DoSomething();  // "Yay!" appears on console. 

Scala中是否有等效的成语?我正在寻找的是:

  1. 最小样板代码
  2. 单个发布者,多个订阅者
  3. 附加/分离订阅者

在 Scala 文档中使用它的例子会很棒。我不是在 Scala 中寻找 C# 事件的实现。相反,我正在寻找 Scala 中的等效习语

4

2 回答 2

2

scala 的惯用方式是不使用观察者模式。请参阅弃用观察者模式

看看这个答案以实现。

于 2013-01-24T14:24:43.130 回答
2

这是一篇很好的文章,如何在 Scala 中实现 C# 事件认为它可能真的很有帮助。

基本事件类;

class Event[T]() {

  private var invocationList : List[T => Unit] = Nil

  def apply(args : T) {
    for (val invoker <- invocationList) {
      invoker(args)
    }
  }

  def +=(invoker : T => Unit) {
    invocationList = invoker :: invocationList
  }

  def -=(invoker : T => Unit) {
    invocationList = invocationList filter ((x : T => Unit) => (x != invoker))
  }

}

和使用;

val myEvent = new Event[Int]()

val functionValue = ((x : Int) => println("Function value called with " + x))
myEvent += functionValue
myEvent(4)
myEvent -= functionValue
myEvent(5)
于 2013-01-24T14:29:18.913 回答