13.Javascript設計模式之觀察者模式—-Observer

來源:互聯網
上載者:User
13.Javascript設計模式之觀察者模式----Observer

今天來整理一下有關觀察者模式的東東。

概念

為了便於理解,首先我舉一個現實生活中的例子:在快樂男生比賽過程其實就是觀察者的一個體現,可以這樣說吉傑是一個被觀察者,
而楊二,包小柏,還有巫啟賢就是3個觀察者,被觀察者操作(唱歌)時,觀察者們就開始操作(評分),被觀察者唱歌就是通知觀察者們進行評分。

GoF說道:Observer模式的意圖是“定義對象間的一種一對多的依賴關係,當一個對象的狀態發生改變時,所有依賴於它的對象都得到通知並被自動更新”。從這段話裡我們可以得到兩個資訊,如下:

1. 觀察者(具體執行操作的對象,有多個)2. 被觀察者(顧名思義是被觀察的對象,如果該對象發生某些變化則通知觀察者執行對應的操)
觀察者模式樣本

一句話,這個模式的實質就是你可以對某個對象的狀態進行觀察,並且在其發生改變時能夠得到通知。因此給出下面這個非常簡單的例子,您可以看看先...

//example using listenersvar element = $('example');var fn1 = function(e) {    //handle click};var fn2 = function(e) {    // do other stuff with click};addEvent(element, 'click', fn1);addEvent(element, 'click', fn2);// example using handlersvar element = document.getElementById('b');var fn1 = function(e) {    // handle click};var fn2 = function(e) {    // do other stuff with click};element.onclick = fn1;element.onclick = fn2; //fn1被覆蓋了

在《Javascript設計模式》一書中,還給出了這樣一個例子:

// Publisher APIvar Animation = function(o) {    this.onStart = new Publisher,    this.onComplete = new Publisher,    this.onTween = new Publisher;};Animation.method('fly', function() {    // begin animation    this.onStart.deliver();    for ( ... ) { // loop through frames    // deliver frame number    this.onTween.deliver(i);    }    // end animation    this.onComplete.deliver();});// setup an account with the animation managervar Superman = new Animation({...config properties...});// Begin implementing subscribersvar putOnCape = function(i) { };var takeOffCape = function(i) { };putOnCape.subscribe(Superman.onStart);takeOffCape.subscribe(Superman.onComplete);// fly can be called anywhereSuperman.fly();// for instance:addEvent(element, 'click', function() {    Superman.fly();});

這個會不會看的有點兒費勁兒呢?呵呵,A za A za Fighting......

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.