【js进阶】设计模式之单例模式的几种声明方式

单例模式,简言之就是一个类无论实例化多少次,最终都是同一个对象

原生js的几个辅助方式的实现

  • 手写forEch,map,filter
js 复制代码
Array.prototype.MyForEach = function (callback) {
  for (let i = 0; i < this.length; i++) {
    callback(this[i], i, this);
  }
};

const arr = [1, 2, 3];
arr.MyForEach((item, index, arr) => {
  console.log(item);
  console.log(index);
  console.log(arr);
});

Array.prototype.MyFilter = function (callback) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    if (callback(this[i], i, this)) {
      result.push(this[i]);
    }
  }
  return result;
};

const arr2 = [1, 2, 3, 5, 6, 7];
console.log(arr2.MyFilter((item) => item > 3));
console.log(arr2.MyFilter((item) => item < 5));

Array.prototype.MyMap = function (callback) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    result.push(callback(this[i], i, this));
  }
  return result;
};

console.log(arr2.MyMap((item) => item * 2));

基础单例模式

js 复制代码
// 单体模式,
var SingleTon = {
  a1: true,
  a2: 10,
  method1() {
    console.log('单体模式1');
  },
  method2() {
    console.log('单体模式2');
  },
};

SingleTon.a1 = false;
let total = SingleTon.a2 + 5;
let result = SingleTon.method1();

// 全局命名空间
let GiantCorp = {};
GiantCorp.Common = {};
GiantCorp.ErrorCodes = {};
GiantCorp.PahgeHandler = {};

// 私有成员,一是相互约定用下划线标注
GiantCorp.DataParse = {
  // 私有属性
  _name: '张三',
  // 私有方法
  _getName() {
    return this._name;
  },
  // 公有方法
  getUsername(nickname) {
    return this._getName() + nickname;
  },
};

改进版单例

js 复制代码
let MyNamespace = {};
// 使用闭包封装私有变量
MyNamespace.SingleTon = (function () {
  let arr = ['张三', '李四', '王五'];
  return {
    name: '续航',
    age: 18,
    getName() {
      return this.name;
    },
    getAge() {
      return this.age;
    },
    getAllUserName() {
      return arr.join(',');
    },
  };
})();

console.log(MyNamespace.SingleTon.getName());
console.log(MyNamespace.SingleTon.getAge());
console.log(MyNamespace.SingleTon.getAllUserName());

高阶版单例

js 复制代码
// 惰性单体
let MyNamespace = {};
// 使用闭包封装私有变量
MyNamespace.SingleTon = (function () {
  let singleTon = null;

  function constructor() {
    let arr = ['张三', '李四', '王五'];
    return {
      name: '续航',
      age: 18,
      getName() {
        return this.name;
      },
      getAge() {
        return this.age;
      },
      getAllUserName() {
        return arr.join(',');
      },
    };
  }
  return {
    getInstance() {
      if (!singleTon) {
        singleTon = constructor(); // 创建实例对象,并将其赋值给私有变量
      }
      return singleTon; // 返回实例对象(单例模式)
    },
  };
})();
console.log(MyNamespace.SingleTon.getInstance().getName());
console.log(MyNamespace.SingleTon.getInstance().getAllUserName());

案例

js 复制代码
let simpleXhrFactory = (function () {
  let standard = {
    createXHRObject() {
      return new XMLHttpRequest();
    },
  };
  let activexOld = {
    createXHRObject() {
      return new ActiveXObject('Microsoft.XMLHTTP');
    },
  };
  let activeXNew = {
    createXHRObject() {
      return new ActiveXObject('MSXML2.XMLHTTP');
    },
  };
  let xhr = null;
  try {
    xhr = standard.createXHRObject();
    return xhr;
  } catch (e) {
    try {
      xhr = activeXNew.createXHRObject();
      return xhr;
    } catch (e) {
      try {
        xhr = activeXOld.createXHRObject();
      } catch (error) {
        throw new Error('不支持的浏览器');
      }
    }
  }
  return xhr;
})();
相关推荐
小帅不太帅13 分钟前
1.5M 参数的 OCR 模型,我把它跑进了浏览器
前端·javascript·ai编程
avi911113 小时前
[AI教做人]AI平台做2项目;一个3D模型展示,另一个框架多人
javascript·人工智能·ai·3d模型·3d引擎·顶点和法线
kyriewen13 小时前
我用Claude Code两天干完了团队两周的排期——周报发出去那一刻我就后悔了
前端·javascript·ai编程
用户9385156350714 小时前
手写一个 LLM Harness 框架:用工程化手段把大模型幻觉踩在脚下
javascript·人工智能·后端
油丶酸萝卜别吃15 小时前
jquery-ajax.js 说明文档
前端·javascript·jquery
windliang15 小时前
Claude Code 源码分析(九):子 Agent 如何分叉、继续与回到父会话
前端·javascript·面试
柒和远方15 小时前
V063: TS 面试必考:interface 与 type 的四大差异,与 LLM Harness 的自动化择优
前端·javascript
汉堡大王952716 小时前
Vue 3 + TS + Element Plus 实战:如何从零搭建企业级违章记录管理 SaaS 前端
前端·javascript·vue.js
海天鹰16 小时前
屏幕颜色检测
javascript·html5
用户79172867619716 小时前
opencode-plugin-peers完全指南:OpenCode如何实现 Claude Code式跨会话消息
javascript