javascript实现proxy模式

来源:互联网 发布:js call和apply的区别 编辑:程序博客网 时间:2024/06/14 00:35
<script>    //代理模式(proxy): 代理也是对象,他的目的就是为了节制(控制)对本体对象的访问 extjs就采用了很多中代理模式    //图书馆(本体对象,实例化读书馆需要消耗很多的资源)    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;    }    Library.prototype = {        constructor:Library,        addbook:function (book) {            this.books[book.id] = book;        },        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;    }    LibraryProxy.prototype = {        constructor:LibraryProxy,        initializeLibray:function () {            if(this.library == null)                    alert('产生真正的本体对象');                    this.library = new Library(this.books);        },        addbook:function (book) {            this.initializeLibray();            this.library.addbook(book);        },        findbook:function (id) {            this.initializeLibray();             return this.library.findbook(id);        },        checkoutbook:function (id) {            //电脑登记。。。叫押金            this.initializeLibray();            return this.library.checkoutbook(id);        },        returnbook:function (book) {            //计算费用            //计算余额            this.initializeLibray();            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('02').author);</script>
0 0
原创粉丝点击