標籤:content log 中括弧 控制 ace set mon return get
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type=text/javascript charset=utf-8 src=../commons/CommonUtil.js ></script> <script type=text/javascript charset=utf-8> //代理模式(proxy):代理也是對象,他的目的就是為了節制(控制)對本體對象的訪問 var LibraryInterface = new BH.Interface(‘LibraryInterface‘ ,[‘addbook‘,‘findbook‘,‘checkoutbook‘,‘returnbook‘]); var Book = function(id , title , author){ this.id = id; this.title = title ; this.author = author; }; //圖書館(本體對象 , 執行個體化圖書館需要消耗很多的資源) var Library = function(books){ this.books = books;//{bookid : book} }; Library.prototype = { constructor:Library , addbook:function(book){ this.books[book.id] = book;//訪問json用中括弧 }, findbook:function(id){ if(this.books[id]){ return this.books[id]; } return null; }, checkoutbook:function(id){ //電腦登記..交押金 return this.findbook(id); }, returnbook:function(book){ //電腦登記(...已還) //計算費用(計算餘額) this.books[book.id] = book; } }; //圖書館的代理對象 var LibraryProxy = function(books){ alert(‘產生代理對象,但是並沒有產生真正的本體對象!‘); this.books = books; this.library = null; //定義一個Null 物件 }; LibraryProxy.prototype = { constructor:LibraryProxy , initializeLibrary:function(){ if(this.library == null){ alert(‘真正的本體對象!‘); this.library = new Library(this.books); } }, addbook:function(book){ this.initializeLibrary(); //實際上具體做事情的還是本體對象自己本身 this.library.addbook(book); }, findbook:function(id){ this.initializeLibrary(); return this.library.findbook(id); }, checkoutbook:function(id){ this.initializeLibrary(); return this.findbook(id); }, returnbook:function(book){ this.initializeLibrary(); this.library.returnbook(book); } }; //執行個體化的是代理對象:延遲本體對象執行個體化的時間,什麼時候具體去做事情了,再去執行個體化它 // hibernate: get(全查詢出來) load(返回代理對象) var proxy = new LibraryProxy({ "01":new Book(‘01‘,‘java‘,‘z3‘), "02":new Book(‘02‘,‘js‘,‘z4‘) }); alert(proxy.findbook(‘01‘).title); </script> </head> <body> </body></html>
js30--代理模式