当前位置:   article > 正文

(二)js前端开发中设计模式之单例模式

(二)js前端开发中设计模式之单例模式

单例模式

保证一个类仅有一个实例,并提供一个访问它的全局访问点。
利弊分析

  • 优点:

    • 单例模式可以保证内存中只有一个对象,减少了内存的开销。
    • 可以避免对资源的多重占用。
    • 方便测试,可以通过接口来控制类的实例化。
    • 避免对资源的多重占用。
  • 缺点:

    • 单例模式一般没有接口,扩展比较困难。
    • 单点访问,可能会导致模块的耦合。
  • 基本的单例模式,就是对象字面量

const SingleTon = {
  name:"tom",
  age"26",
  say(){
    console.log("hello")
  },
  eat(){
    console.log("rice")
  }
}

//访问单例
SingleTon.gender = '男'
SingleTon.say()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

划分命名空间

var GianCrop = {};
GianCrop.common = {};
GianCrop.errorCodes = {};
GianCrop.pageHandler = {};
  • 1
  • 2
  • 3
  • 4

使用私有成员

  • 方式一:约定
GianCrop.dataParse = {
  //约定私有成员以_开头
  _method1() {},
  _method2() {},
  _method3() {}
  //约定公共成员不以_开头
  method1() {},
  method2() {},
  method3() {}
};

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 方式二:闭包
// MyNameSpce.SingleTon = {}
// 闭包单例模式
let MyNameSpce = {};
MyNameSpce.SingleTon = (function () {
  return {
    name: "tom",
    age: 26,
    say() {
      console.log("hello");
    },
    eat() {
      console.log("rice");
    },
  };
})();

const name = MyNameSpce.SingleTon.name;
console.log("
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/865655
推荐阅读
相关标签