javascript實現proxy模式

<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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章