命令模式的應用場景:
有時候需要向某些對象發送請求,但是並不知道請求的接收者是誰,也不知道被請求的操作是什麼,此時希望用一種松耦合的方式來設計軟件,使得請求發送者和請求接收者能夠消除彼此之間的耦合關系。
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代碼:
// 在頁面中使用例: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的學習,心裡隱隱的留下了關於命令模式的影子。
參考:
《JavaScript設計模式與開發實踐》第9章9.2節
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。