深入理解JavaScript系列(31):設計模式之代理模式

來源:互聯網
上載者:User
介紹

代理,顧名思義就是協助別人做事,GoF對代理模式的定義如下:

代理模式(Proxy),為其他對象提供一種代理以控制對這個對象的訪問。

代理模式使得代理對象控制具體對象的引用。代理幾乎可以是任何對象:檔案,資源,記憶體中的對象,或者是一些難以複製的東西。

本文

我們來舉一個簡單的例子,假如dudu要送優酪乳小妹玫瑰花,卻不知道她的連絡方式或者不好意思,想委託大叔去送這些玫瑰,那大叔就是個代理(其實挺好的,可以扣幾朵給媳婦),那我們如何來做呢?

// 先聲明美女對象
var girl = function (name) {
this.name = name;
};

// 這是dudu
var dudu = function (girl) {
this.girl = girl;
this.sendGift = function (gift) {
alert("Hi " + girl.name + ", dudu送你一個禮物:" + gift);
}
};

// 大叔是代理
var proxyTom = function (girl) {
this.girl = girl;
this.sendGift = function (gift) {
(new dudu(girl)).sendGift(gift); // 替dudu送花咯
}
};

調用方式就非常簡單了:

var proxy = new proxyTom(new girl("優酪乳小妹"));
proxy.sendGift("999朵玫瑰");

實戰一把

通過上面的代碼,相信大家對代理模式已經非常清楚了,我們來實戰下:我們有一個簡單的播放清單,需要在點擊單個串連(或者全選)的時候在該串連下方顯示視頻曲介紹以及play按鈕,點擊play按鈕的時候播放視頻,列表結構如下:

<h1>Dave Matthews vids</h1>
<p><span id="toggle-all">全選/反選</span></p>
<ol id="vids">
<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--2158073">Gravedigger</a></li>
<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--4472739">Save Me</a></li>
<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--45286339">Crush</a></li>
<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--2144530">Don't Drink The Water</a></li>
<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--217241800">Funny the Way It Is</a></li>
<li><input type="checkbox" checked><a href="http://new.music.yahoo.com/videos/--2144532">What Would You Say</a>
</li>
</ol>

我們先來分析如下,首先我們不僅要監控a串連的點擊事件,還要監控“全選/反選”的點擊事件,然後請求伺服器查詢視頻資訊,組裝HTML資訊顯示在li元素的最後位置上,效果如下:

然後再監控play串連的點擊事件,點擊以後開始播放,效果如下:

好了,開始,沒有jQuery,我們自訂一個選取器:

var $ = function (id) {
return document.getElementById(id);
};

由於Yahoo的json服務提供了callback參數,所以我們傳入我們自訂的callback以便來接受資料,具體查詢字串拼裝代碼如下:

var http = {
makeRequest: function (ids, callback) {
var url = 'http://query.yahooapis.com/v1/public/yql?q=',
sql = 'select * from music.video.id where ids IN ("%ID%")',
format = "format=json",
handler = "callback=" + callback,
script = document.createElement('script');

sql = sql.replace('%ID%', ids.join('","'));
sql = encodeURIComponent(sql);

url += sql + '&' + format + '&' + handler;
script.src = url;

document.body.appendChild(script);
}
};

代理對象如下:

var proxy = {
ids: [],
delay: 50,
timeout: null,
callback: null,
context: null,
// 佈建要求的id和callback以便在播放的時候觸發回調
makeRequest: function (id, callback, context) {

// 添加到隊列dd to the queue
this.ids.push(id);

this.callback = callback;
this.context = context;

// 設定timeout
if (!this.timeout) {
this.timeout = setTimeout(function () {
proxy.flush();
}, this.delay);
}
},
// 觸發請求,使用代理職責調用了http.makeRequest
flush: function () {
// proxy.handler為請求yahoo時的callback
http.makeRequest(this.ids, 'proxy.handler');
// 請求資料以後,緊接著執行proxy.handler方法(裡面有另一個設定的callback)

// 清楚timeout和隊列
this.timeout = null;
this.ids = [];

},
handler: function (data) {
var i, max;

// 單個視頻的callback調用
if (parseInt(data.query.count, 10) === 1) {
proxy.callback.call(proxy.context, data.query.results.Video);
return;
}

// 多個視頻的callback調用
for (i = 0, max = data.query.results.Video.length; i < max; i += 1) {
proxy.callback.call(proxy.context, data.query.results.Video[i]);
}
}
};

視頻處理模組主要有3種子功能:擷取資訊、展示資訊、播放視頻:

var videos = {
// 初始化播放器代碼,開始播放
getPlayer: function (id) {
return '' +
'<object width="400" height="255" id="uvp_fop" allowFullScreen="true">' +
'<param name="movie" value="http://d.yimg.com/m/up/fop/embedflv/swf/fop.swf"\/>' +
'<param name="flashVars" value="id=v' + id + '&amp;eID=1301797&amp;lang=us&amp;enableFullScreen=0&amp;shareEnable=1"\/>' +
'<param name="wmode" value="transparent"\/>' +
'<embed ' +
'height="255" ' +
'width="400" ' +
'id="uvp_fop" ' +
'allowFullScreen="true" ' +
'src="http://d.yimg.com/m/up/fop/embedflv/swf/fop.swf" ' +
'type="application/x-shockwave-flash" ' +
'flashvars="id=v' + id + '&amp;eID=1301797&amp;lang=us&amp;ympsc=4195329&amp;enableFullScreen=1&amp;shareEnable=1"' +
'\/>' +
'<\/object>';
},
// 拼接資訊顯示內容,然後在append到li的底部裡顯示
updateList: function (data) {
var id,
html = '',
info;

if (data.query) {
data = data.query.results.Video;
}
id = data.id;
html += '<img src="' + data.Image[0].url + '" width="50" \/>';
html += '<h2>' + data.title + '<\/h2>';
html += '<p>' + data.copyrightYear + ', ' + data.label + '<\/p>';
if (data.Album) {
html += '<p>Album: ' + data.Album.Release.title + ', ' + data.Album.Release.releaseYear + '<br \/>';
}
html += '<p><a class="play" href="http://new.music.yahoo.com/videos/--' + id + '">&raquo; play<\/a><\/p>';
info = document.createElement('div');
info.id = "info" + id;
info.innerHTML = html;
$('v' + id).appendChild(info);
},
// 擷取資訊並顯示
getInfo: function (id) {
var info = $('info' + id);

if (!info) {
proxy.makeRequest(id, videos.updateList, videos); //執行代理職責,並傳入videos.updateList回呼函數
return;
}

if (info.style.display === "none") {
info.style.display = '';
} else {
info.style.display = 'none';
}
}
};

現在可以處理點擊事件的代碼了,由於有很多a串連,如果每個串連都綁定事件的話,顯然效能會有問題,所以我們將事件綁定在<ol>元素上,然後檢測點擊的是否是a串連,如果是說明我們點擊的是視頻地址,然後就可以播放了:

$('vids').onclick = function (e) {
var src, id;

e = e || window.event;
src = e.target || e.srcElement;

// 不是串連的話就不繼續處理了
if (src.nodeName.toUpperCase() !== "A") {
return;
}
//停止冒泡
if (typeof e.preventDefault === "function") {
e.preventDefault();
}
e.returnValue = false;

id = src.href.split('--')[1];

//如果點擊的是已經生產的視頻資訊地區的串連play,就開始播放
// 然後return不繼續了
if (src.className === "play") {
src.parentNode.innerHTML = videos.getPlayer(id);
return;
}

src.parentNode.id = "v" + id;
videos.getInfo(id); // 這個才是第一次點擊的時候顯示視頻資訊的處理代碼
};

全選反選的代碼大同小異,我們就不解釋了:

$('toggle-all').onclick = function (e) {

var hrefs, i, max, id;

hrefs = $('vids').getElementsByTagName('a');
for (i = 0, max = hrefs.length; i < max; i += 1) {
// 忽略play串連
if (hrefs[i].className === "play") {
continue;
}
// 忽略沒有選擇的項
if (!hrefs[i].parentNode.firstChild.checked) {
continue;
}

id = hrefs[i].href.split('--')[1];
hrefs[i].parentNode.id = "v" + id;
videos.getInfo(id);
}
};

完整代碼:https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/proxy.html

總結

代理模式一般適用於如下場合:

  1. 遠程代理,也就是為了一個對象在不同的地址空間提供局部代表,這樣可以隱藏一個對象存在於不同地址空間的事實,就像web service裡的代理類一樣。
  2. 虛擬代理,根據需要建立開銷很大的對象,通過它來存放執行個體化需要很長時間的真實對象,比如瀏覽器的渲染的時候先顯示問題,而圖片可以慢慢顯示(就是通過虛擬代理代替了真實的圖片,此時虛擬代理儲存了真實圖片的路徑和尺寸。
  3. 安全代理,用來控制真實對象訪問時的許可權,一般用於對象應該有不同的存取權限。
  4. 智能指引,只當調用真實的對象時,代理處理另外一些事情。例如C#裡的記憶體回收,使用對象的時候會有引用次數,如果對象沒有引用了,GC就可以回收它了。
    參考:《大話設計模式》

轉自:湯姆大叔

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.