JS設(shè)計(jì)模式2 - 觀察者模式和推送注冊模式

觀察者模式

觀察者模式

目的

通知對象的變化到另一些對象

何時(shí)使用

  1. 某些對象的狀態(tài)改變需要觸發(fā)另一些對象的改變
  2. 廣播能力

常見使用場景
在GUI系統(tǒng)中,一些按鈕,菜單發(fā)出的通知。

代碼實(shí)現(xiàn)

https://github.com/benhaben/essentialjsdesignpatterns.git

下面的代碼實(shí)現(xiàn)了點(diǎn)擊一個(gè)checkbox,通知所有其他的checkbox。checkbox可以通過“Add New Observer checkbox”按鈕來增加。

代碼功能

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>觀察者模式</title>
</head>
<body>
<button id="addNewObserver">Add New Observer checkbox</button>
<input id="mainCheckbox" type="checkbox"/>
<div id="observersContainer"></div>

<script type="text/javascript" src="observer.js"></script>

</body>
</html>

js:

function Subject(){
    this.observers = new ObserverList();

    function ObserverList(){
        this.observerList = [];
    }

    ObserverList.prototype.add = function( obj ){
        return this.observerList.push( obj );
    };

    ObserverList.prototype.count = function(){
        return this.observerList.length;
    };

    ObserverList.prototype.get = function( index ){
        if( index > -1 && index < this.observerList.length ){
            return this.observerList[ index ];
        }
    };

    ObserverList.prototype.indexOf = function( obj, startIndex ){
        var i = startIndex;

        while( i < this.observerList.length ){
            if( this.observerList[i] === obj ){
                return i;
            }
            i++;
        }

        return -1;
    };

    ObserverList.prototype.removeAt = function( index ){
        this.observerList.splice( index, 1 );
    };
}

Subject.prototype.addObserver = function( observer ){
    this.observers.add( observer );
};

Subject.prototype.removeObserver = function( observer ){
    this.observers.removeAt( this.observers.indexOf( observer, 0 ) );
};

Subject.prototype.notify = function( context ){
    var observerCount = this.observers.count();
    for(var i=0; i < observerCount; i++){
        this.observers.get(i).update( context );
    }
};
// ------------------------------------------------------------

function Observer(){
    this.update = function(){
        // ...
    };
}

// ------------------------------------------------------------

// Extend an object with an extension
function extend( obj, extension ){
    for ( var key in extension ){
        obj[key] = extension[key];
    }
}

// References to our DOM elements

var controlCheckbox = document.getElementById( "mainCheckbox" ),
    addBtn = document.getElementById( "addNewObserver" ),
    container = document.getElementById( "observersContainer" );


// Concrete Subject

// Extend the controlling checkbox with the Subject class
extend( controlCheckbox, new Subject() );

// Clicking the checkbox will trigger notifications to its observers
controlCheckbox.onclick = function(){
    controlCheckbox.notify( controlCheckbox.checked );
};

addBtn.onclick = addNewObserver;

// Concrete Observer

function addNewObserver(){

    // Create a new checkbox to be added
    var check = document.createElement( "input" );
    check.type = "checkbox";

    // Extend the checkbox with the Observer class
    extend( check, new Observer() );

    // Override with custom update behaviour
    check.update = function( value ){
        this.checked = value;
    };

    // Add the new observer to our list of observers
    // for our main subject
    controlCheckbox.addObserver( check );

    // Append the item to the container
    container.appendChild( check );
}

Publish/Subscribe Pattern

在JS的世界中有一種類似的模式,叫推送/注冊模式,可以讓observer和subject解耦。
推送/注冊模式可以設(shè)置一個(gè)“頻道”,讓感興趣的注冊這實(shí)現(xiàn)一個(gè)函數(shù)去注冊。
感覺推送/注冊模式更能發(fā)揮js的“動(dòng)態(tài)特性”,而observe更適合具有靜態(tài)特性和具有接口的語言。

代碼實(shí)現(xiàn)

下面的列子基于inbox/newMessage這個(gè)頻道,其實(shí)也就是一個(gè)字符串來標(biāo)示一下??梢杂胣ode來跑這個(gè)例子。

/**
 * Created by shenyin.sy on 17/3/16.
 */

"use strict"
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {
    subscribe(eventName, listener) {
        this.on(eventName, listener);
    }

    publish() {
        var args = Array.prototype.slice.call(arguments);
        this.emit.apply(this, args);
    }
}

const myEmitter = new MyEmitter();

// A very simple new mail handler

// A count of the number of messages received
var mailCounter = 0;

// Initialize subscribers that will listen out for a topic
// with the name "inbox/newMessage".

// Render a preview of new messages
myEmitter.subscribe("inbox/newMessage", function (topic, data) {

    // Log the topic for debugging purposes
    console.log("A new message was received, show topic: ", topic);

});

// Here's another subscriber using the same data to perform
// a different task.

// Update the counter displaying the number of new
// messages received via the publisher

myEmitter.subscribe("inbox/newMessage", function (topic, data) {
    console.log("A new message was received, show data: ", data);

});

myEmitter.publish("inbox/newMessage", [{
    sender: "hello@google.com",
    body: "Hey there! How are you doing today?"
}], "this is data");

// We could then at a later point unsubscribe our subscribers
// from receiving any new topic notifications as follows:
// unsubscribe( subscriber1 );
// unsubscribe( subscriber2 );

總結(jié)

對象的狀態(tài)改變,需要通知給另一些對象,使用這個(gè)模式是比較靠譜的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容