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


原创粉丝点击