javascript 代理模式
通过图来讲解什么是惰性代理(第二个案例)
普通代理模式(用处不大,基本不用,主要做案例说明代理模式是什么)
/*
* 普通代理模式
* */
//图书类
var Book = function (bid,bName,bPrice) {
this.bid = bid;
this.bName = bName;
this.bPrice = bPrice;
}
//目标类
var BookShop = (function () {
var books = {};
return function (bks) {
if(typeof bks == "object"){
books = bks;
};
//加书
this.addBook = function (book) {
books[book.bid] = book;
};
//找书
this.findBook =function (bid) {
if(books[bid]){
return books[bid];
}else{
return null;
}
};
//还书
this.returnBook=function (book) {
this.addBook(book);
};
//借书
this.checkBook=function (bid) {
var book = this.findBook(bid);
return book;
}
}
})();
//普通代理
var proxyBookShop = function (bks) {
var obj = new BookShop(bks);
//加书
this.addBook = function (book) {
obj.addBook(book);
};
//找书
this.findBook =function (bid) {
return obj.findBook(bid);
};
//还书
this.returnBook=function (book) {
obj.returnBook(book)
};
//借书
this.checkBook=function (bid) {
return obj.checkBook(bid);
}
}
var proxy = new proxyBookShop({
"001":new Book('001','js',85),
"002":new Book('002','html',30),
"003":new Book('003','css',45),
});
console.log(proxy.checkBook("001").bName);
惰性代理模式
/*
* 惰性代理
*
* */
//图书类
var Book = function (bid,bName,bPrice) {
this.bid = bid;
this.bName = bName;
this.bPrice = bPrice;
}
//目标类
var BookShop = (function () {
var books = {};
return function (bks) {
if(typeof bks == "object"){
books = bks;
};
//加书
this.addBook = function (book) {
books[book.bid] = book;
};
//找书
this.findBook =function (bid) {
if(books[bid]){
return books[bid];
}else{
return null;
}
};
//还书
this.returnBook=function (book) {
this.addBook(book);
};
//借书
this.checkBook=function (bid) {
var book = this.findBook(bid);
return book;
}
}
})();
var proxyBookShop = function (bks) {
var obj =null;
this._init = function () {
console.log("在调用内部方法时,初始化本类");
obj = new BookShop(bks);
}
//加书
this.addBook = function (book) {
this._init();
obj.addBook(book);
};
//找书
this.findBook =function (bid) {
this._init();
return obj.findBook(bid);
};
//还书
this.returnBook=function (book) {
this._init();
obj.returnBook(book)
};
//借书
this.checkBook=function (bid) {
this._init();
return obj.checkBook(bid);
}
};
var proxy = new proxyBookShop({
"001":new Book('001','js',85),
"002":new Book('002','html',30),
"003":new Book('003','css',45),
});
console.log(proxy.checkBook("001").bName);