12-JavaScript设计模式——代理模式
来源:互联网 发布:mac的常用快捷键 编辑:程序博客网 时间:2024/05/16 18:13
代理模式 作用:节制或延迟对象的加载;
说白了,当我用到这个 对象的方法 的时候,才会去创建该 对象。
代码实例:
// 代理对象:代理也是对象,他的目的就是为了节制(控制)对本体对象的访问;// 图书馆(本体对象,实例化图书馆需要消耗很多的资源)var LibraryInterface = new JG.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){ this.books = books; this.library = null;// 定义一个空对象};LibraryProxy.prototype = { constructor : LibraryProxy, // 初始化本体对象的函数 initLibrary : function(){ if(!this.library){ this.library = new Library(this.books); } }, addBook : function(book){ this.initLibrary(); this.library.addBook(book); }, findBook : function(id){ this.initLibrary(); if(this.library.books[id]){ return this.library.books[id]; } return null; }, // 借书 checkoutBook : function(id){ this.initLibrary(); // 电脑登记...交押金(伪代码) return this.library.findBook(id); }, // 还书 returnBook : function(book){ this.initLibrary(); // 电脑登记(已还)...计算费用(伪代码) this.library.books[book.id] = book; }};// 实例化的是代理对象,推迟本体对象实例化的时间var proxy = new LibraryProxy({ '01':new Book('01', 'java', 'zhangSan'), '02':new Book('02', 'js', 'liSi')});alert(proxy.findBook('02').title);// js
阅读全文
1 0
- 12-JavaScript设计模式——代理模式
- javascript设计模式之三——代理模式
- 设计模式—代理模式
- 设计模式—代理模式
- 设计模式—代理模式
- 设计模式—代理模式
- 设计模式—代理模式
- 设计模式—代理模式
- 设计模式—代理模式
- 设计模式—代理模式
- 设计模式—代理模式
- 设计模式—代理模式
- JavaScript设计模式--代理模式
- javascript 设计模式-代理模式
- 设计模式——代理设计模式
- 设计模式——代理设计模式
- JavaScript代理设计模式原理
- 每日设计模式——代理模式
- HBase单机踩过的坑
- Android中解决包冲突的问题(简单暴力)
- Android常用控件-02
- Android-Smali-入门介绍/基础语法
- 二叉搜索树
- 12-JavaScript设计模式——代理模式
- PE 75
- 数据分析Numpy库入门
- ImageView控件
- Xcode文档前大写字母的含义:
- [BZOJ1492][NOI2007]货币兑换Cash-斜率优化DP-CDQ分治
- "FAIL-Failed to deploy application at context path /test"问题原因
- 前端面试以及总结
- 利用NFS挂载文件目录到Linux开发板