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......