2013-01-24 41 views
9

在C#中的類和接口可以有event S:什麼是Scala中慣用的等效C#的事件

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中尋找C#事件的實現。相反,我在斯卡拉尋找等效的成語

+1

這可能是有益的:http://stackoverflow.com/questions/6814246/in-scala-how-would-i-combine-event-driven-programming-with-a-functional-approac – daryal

回答

2

scala的習慣用法不是使用觀察者模式。 見Deprecating the Observer Pattern

查看this answer的實施。

+3

如何是否說「不使用觀察者問題」幫助OP(就實際回答他的問題而言)? –

+1

我猜「不要這樣做,以某種相關的方式去做」是senia的意思。 – Jesper

+0

@KirkWoll:OP upvoted的答案,必須做正確的=) – FMM

2

This is a nice article how to implement C# events in Scala認爲這可能是非常有幫助的。

基礎事件類;

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) 
+0

從這個問題:「我不想在Scala中實現C#事件。」 – FMM

+2

如果你發佈了一個鏈接,請提供至少基本的摘錄:隨着時間的推移,頁面可能會變得不可用,未來的讀者將沒有任何方向去挖掘。 –

相關問題