单体模式:保证一个特定类仅有一个实例;即第二次使用同一个类创建新对象时,应该得到与第一个所创建对象完全相同对象;

  • 在JS中,可以认为每次在使用对象字面量创建对象的时候,实际上就在创建一个单体;
  • 当使用new创建新对象时
    • 使用静态属性中的实例:

      1. function Universe() {
      2. if(typeof Universe.instance === 'object') {
      3. return Universe.instance;
      4. }
      5. this.start_time = 0;
      6. this.bang = 'Big';
      7. Universe.instance = this;
      8. return this;
      9. }  
    • 采用闭包包含单个实例:
      1. function Universe1() {
      2. var instance = this;
      3. this.start_time = 0;
      4. this.bang = 'Big';
      5. Universe1 = function() {
      6. return instance;
      7. }
      8. }
      1. var Universe;
      2. (function () {
      3. var instance;
      4. Universe = function Universe() {
      5. if(instance) {
      6. return instance;
      7. }
      8. instance = this;
      9. //增加功能
      10. this.start_time = 0;
      11. this.bang = 'Big';
      12. }
      13. })();

工厂模式:

根据字符串指定地类型在运行时创建对象地方法

工厂模式地目的使为了创建对象

  • 当创建对象时执行重复操作
  • 再编译时不知道具体类型地情况下,为工厂客户提供一个创建对象的接口
  1. function CarMaker() {};
  2.  
  3. CarMaker.prototype.drive = function() {
  4. return "Vroom, I have " + this.doors + " doors";
  5. };
  6. CarMaker.factory = function(type) {
  7. var constr = type, newcar;
  8. //如果构造函数不存在,则抛出错误
  9. if(typeof CarMaker[constr] != "function") {
  10. throw {
  11. name: "Error",
  12. message: constr + " doesn't exist"
  13. };
  14. }
  15. //构造函数是已知存在的;使原型继承父类,但仅继承一次
  16. if(typeof CarMaker[constr].prototype.drive !== 'function') {
  17. CarMaker[constr].prototype = new CarMaker();
  18. }
  19. //创建一个新的实例
  20. newcar = new CarMaker[constr]();
  21. //选择性地调用一些方法,然后返回
  22. return newcar;
  23. };
  24.  
  25. CarMaker.Compact = function() {
  26. this.doors = 4;
  27. };
  28. CarMaker.Convertible = function() {
  29. this.doors = 2;
  30. }
  31. CarMaker.SUV = function() {
  32. this.doors = 24;
  33. }
  34.  
  35. var corolla = CarMaker.factory('Compact');
  36. var solstice = CarMaker.factory('Convertible');
  37. var cherokee = CarMaker.factory('SUV');
  38. corolla.drive();
  39. solstice.drive();
  40. cherokee.drive();

内置对象工厂:对于自然工厂的例子,可以考虑内置的Object()构造函数;它也根据输入类型而创建不同的对象;

迭代器模式:

提供一个API来遍历或操纵复杂地自定义数据结构

迭代访问一个包含某些数据集合的对象的模式;

  1. var agg = (function() {
  2. var index = 0, data = [1,2,3,4,5], length = data.length;
  3. return {
  4. next: function() {
  5. var element;
  6. if(!this.hasNext()) {
  7. return null;
  8. }
  9. element = data[index];
  10. index = index + 2;
  11. return element;
  12. },
  13. hasNext: function() {
  14. return index < length;
  15. },
  16. //重置指针到初始化位置
  17. rewind: function() {
  18. index = 0;
  19. },
  20. //返回当前元素
  21. current: function() {
  22. return data[index];
  23. }
  24. }
  25. }());
  26. //测试
  27. while(agg.hasNext()) {
  28. console.log(agg.next());
  29. }
  30. agg.rewind();
  31. console.log(agg.current());

装饰者模式

可以再运行时动态添加附加功能到对象中;比较方便的特征时其预期行为可制定和可配置;

  1. function Sale(price) {
  2. this.price = price || 100;
  3. }
  4. Sale.prototype.getPrice = function() {
  5. return this.price;
  6. }
  7. Sale.decorators = {};
  8. //增加联邦税
  9. Sale.decorators.fedtax = {
  10. getPrice: function() {
  11. var price = this.uber.getPrice();
  12. price += price * 5/ 100;
  13. return price;
  14. }
  15. };
  16. //增加省级税
  17. Sale.decorators.quebec = {
  18. getPrice: function() {
  19. var price = this.uber.getPrice();
  20. price += price * 7.5 /100;
  21. return price;
  22. }
  23. };
  24. //转化为美元
  25. Sale.decorators.money = {
  26. getPrice: function() {
  27. return "$" + this.uber.getPrice().toFixed(2);
  28. }
  29. };
  30. //格式化为CDN
  31. Sale.decorators.cdn = {
  32. getPrice: function() {
  33. return "CDN$ " + this.uber.getPrice().toFixed(2);
  34. }
  35. };
  36. Sale.prototype.decorate = function(decorator) {
  37. var F = function() {},
  38. overrides = this.constructor.decorators[decorator],
  39. i, newobj;
  40. F.prototype = this;
  41. newobj = new F();
  42. newobj.uber = F.prototype;
  43. for(i in overrides) {
  44. if(overrides.hasOwnProperty(i)) {
  45. newobj[i] = overrides[i];
  46. }
  47. }
  48. return newobj;
  49. }
  50.  
  51. var sale = new Sale(100);
  52. sale = sale.decorate('fedtax');
  53. sale = sale.decorate('quebec');
  54. sale = sale.decorate('money');
  55. sale.getPrice();
  56. var newsale = new Sale(200);
  57. newsale = newsale.decorate('cdn');
  58. newsale.getPrice();

使用列表实现

  1. function Sale(price) {
  2. this.price = price;
  3. this.decorators_list = [];
  4. }
  5. Sale.decorators = {};
  6. Sale.decorators.fedtax = {
  7. getPrice: function(price) {
  8. return price + price * 5 / 100;
  9. }
  10. };
  11. Sale.decorators.quebec = {
  12. getPrice: function(price) {
  13. return price + price * 7.5 /100;
  14. }
  15. };
  16. Sale.decorators.money = {
  17. getPrice: function(price) {
  18. return "$" + price.toFixed(2);
  19. }
  20. };
  21. Sale.prototype.decorate = function(decorator) {
  22. this.decorators_list.push(decorator)
  23. };
  24. Sale.prototype.getPrice = function() {
  25. var price = this.price, i, max = this.decorators_list.length, name;
  26. for(i = 0; i < max; i++) {
  27. name = this.decorators_list[i];
  28. price = Sale.decorators[name].getPrice(price);
  29. }
  30. return price;
  31. }
  32.  
  33. var sale = new Sale(100);
  34. sale.decorate('fedtax');
  35. sale.decorate('quebec');
  36. sale.decorate('money');
  37. console.log(sale.getPrice());

  

 

  

javascript优化--10模式(设计模式)01的更多相关文章

  1. javascript优化--11模式(设计模式)02

    策略模式 在选择最佳策略以处理特定任务(上下文)的时候仍然保持相同的接口: //表单验证的例子 var data = { firs_name: "Super", last_name ...

  2. javascript优化--06模式(对象)01

    命名空间: 优点:可以解决命名混乱和第三方冲突: 缺点:长嵌套导致更长的查询时间:更多的字符: 通用命名空间函数: var MYAPP = MYAPP || {}; MYAPP.namespace = ...

  3. javascript优化--12模式(设计模式)03

    观察者模式 通过创建一个可观察的对象,当发生一个感兴趣的事件时将该事件通告给所有观察者,从而形成松散的耦合 订阅杂志 //发布者对象 var publisher = { subscribers: { ...

  4. javascript优化--08模式(代码复用)01

    优先使用对象组合,而不是类继承: 类式继承:通过构造函数Child()来获取来自于另一个构造函数Parent()的属性: 默认模式:子类的原型指向父类的一个实例 function inherit(C, ...

  5. javascript优化--13模式1(DOM和浏览器模式)

    注意分离: 通过将CSS关闭来测试页面是否仍然可用,内容是否依然可读: 将JavaScript关闭来测试页面仍然可以执行正常功能:所有连接是否正常工作:所有的表单是否可以正常工作: 不使用内联处理器( ...

  6. javascript优化--14模式2(DOM和浏览器模式)

    远程脚本 XMLHttpRequest JSONP 和XHR不同,它不受同域的限制: JSONP请求的可以是任意的文档: 请求的URL通常格式为http://example.js?calback=Ca ...

  7. javascript优化--05模式(函数)

    回调函数模式: 基本例子: var findNodes = function (callback) { ...................... if (typeof callback !== ' ...

  8. javascript优化--09模式(代码复用)02

    原型继承 ://现代无类继承模式 基本代码: var parent = { name : "Papa" } var child = object(parent); function ...

  9. javascript优化--07模式(对象)02

    沙箱模式: 解决空间命名模式的几个缺点: 命名空间模式中无法同时使用一个应用程序或库的两个版本运行在同一个页面中,因为两者需要相同的全局符号: 以点分割,需要输入更长的字符,解析时间也更长: 全局构造 ...

随机推荐

  1. Matlab之字符串处理

    Matlab处理字符串 1.取得部分字符串 我们有一个字符串 file='20131030_113109.TemporaryAlias.Poly5'; 简单操作举例: >> a=file( ...

  2. Parencodings(imitate)

    Parencodings Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 20679   Accepted: 12436 De ...

  3. IE下的haslayout特性

    什么是hasLayout?hasLayout是IE特有的一个属性.很多的ie下的css bug都与其息息相关.在ie中,一个元素要么自己对自身的内容进行计算大小和组织,要么依赖于父元素来计算尺寸和组织 ...

  4. 一个1年前的T-SQL问题

    还记得年前的一个SQL问题,当时对SQL刚接触,因此绕开了它.用了别的办法.昨天看SQL突然想起了这个问题.百思不得其解,然后去SQL Server技术交流群,也请教了,大神高文佳,何志勇提示我因为先 ...

  5. [Effective JavaScript 笔记]第4章:对象和原型--个人总结

    前言 对象是js中的基本数据结构.对象在js语言编码中也随处可见,比如经常会用到的函数,也是一个Function构造函数,Function.prototype原型对象.每当声明一个函数时,都会继承Fu ...

  6. sql分页查询语句

    有关分页 SQL 的资料很多,有的使用存储过程,有的使用游标.本人不喜欢使用游标,我觉得它耗资.效率低:使用存储过程是个不错的选择,因为存储过程是经过预编译的,执行效率高,也更灵活.先看看单条 SQL ...

  7. HDU1879 kruscal 继续畅通工程

    继续畅通工程 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Subm ...

  8. php页面打开响应时间

    $start_time = array_sum(explode(' ',microtime())); //your code here   $end_time = array_sum(explode( ...

  9. cookie注入的形成,原理,利用总结

    一:cookie注入的形成 程序对提交数据获取方式是直接request("c.s.t")的方式.未指明使用request对象的具体方法进行获取. 二:原理 request(&quo ...

  10. 【Python】python代码如何调试?

    Python 程序如何高效地调试? 现在我在debug python程序就只是简单在有可能错误的地方print出来看一下,不知道python有没像c++的一些IDE一样有单步调试这类的工具?或者说各位 ...