命令模式的應用場景:javascript
有時候須要向某些對象發送請求,可是並不知道請求的接收者是誰,也不知道被請求的操做是什麼,此時但願用一種鬆耦合的方式來設計軟件,使得請求發送者和請求接收者可以消除彼此之間的耦合關係。css
html代碼:html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>js:命令模式</title> <script type="text/javascript" src="command.js"></script> </head> <style type="text/css"> button{ margin: 5px; border: 0; width: 70px; height: 35px; background: #6B78BF; color: white; font-size: 14px; font-family: "微軟雅黑"; cursor: pointer; } #textarea{ margin: 5px; width: 400px; height: 200px; resize: none; color: #666; font-size: 14px; border: 2px solid #6B78BF; } </style> <body> <button id="button1">刷新</button> <button id="button2">新增</button> <button id="button3">刪除</button> <br/> <textarea id="textarea"> 這是預設的內容 </textarea> </body> </html>
js代碼:java
// 在頁面中使用例:setCommand( button1, refreshMenuBarCommand );來發送命令 // setCommand 函數負責往按鈕上面安裝命令,預留好安裝命令的接口 var setCommand = function( button , command ){ button.onclick = function(){ command.execute(); } } // 編寫點擊按鈕以後的具體行爲:刷新菜單界面、增長子菜單和刪除子菜單 var MenuBar = { refresh: function(){ var cur_date = new Date(); document.getElementById("textarea").value+=cur_date.toLocaleString()+" 刷新菜單目錄\r"; } } var SubMenu = { add: function(){ var cur_date = new Date(); document.getElementById("textarea").value+=cur_date.toLocaleString()+" 新增菜單目錄\r"; }, del: function(){ var cur_date = new Date(); document.getElementById("textarea").value+=cur_date.toLocaleString()+" 刪除子菜單\r"; } } //封裝行爲在命令類中 var RefreshMenuBarCommand = function( receiver ){ this.receiver = receiver; } RefreshMenuBarCommand.prototype.execute = function(){ this.receiver.refresh(); } var AddSubMenuCommand = function( receiver ){ this.receiver = receiver; } AddSubMenuCommand.prototype.execute = function(){ this.receiver.add(); } var DelSubMenuCommand = function( receiver ){ this.receiver =receiver } DelSubMenuCommand.prototype.execute = function(){ this.receiver.del(); } //命令接收者傳入到 command 對象 var refreshMenuBarCommand = new RefreshMenuBarCommand( MenuBar ); var addSubMenuCommand = new AddSubMenuCommand( SubMenu ); var delSubMenuCommand = new DelSubMenuCommand( SubMenu ); window.onload = function(){ //把 command 對象安裝到 button 上面 var button1 = document.getElementById("button1"); var button2 = document.getElementById("button2"); var button3 = document.getElementById("button3"); setCommand( button1, refreshMenuBarCommand ); setCommand( button2, addSubMenuCommand ); setCommand( button3, delSubMenuCommand ); }
總結:設計模式
從書上抄代碼練習的過程當中出了不少錯誤,最嚴重的莫過於「receiver」這個單詞寫錯了致使數日都再沒看這個練習,出錯的過程讓我可以從新審視代碼的內容,逐行進行理解與調試。雖然仍然不很理解命令模式,可是經過這部分的內容和對mySQL的學習,內心隱隱的留下了關於命令模式的影子。函數
參考:學習