美文网首页
单例模式

单例模式

作者: 我家有个王胖胖 | 来源:发表于2023-04-11 10:48 被阅读0次

    定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
    单例模式是一种常用的模式,有些对象往往只需要一个,比如:线程池、全局缓存、浏览器中的 window 对象等。在 Javascript 开发中,单例模式的用途同样非常广泛,比如做登录弹框,它在当前页面是唯一的,无论单击多少次,都只会创建一次,这就非常适合用单例模式来创建。

    class Person {
            constructor(name, age) {
              this.name = name;
              this.age = age;
            }
          }
          let p1 = new Person();
          let p2 = new Person();
          console.log(p1 === p2);//fasle
    

    1.简单实现:

    class Person {
      constructor(name, age) {
        console.log('person created');
      }
    }
    //创建Person的工作提前了入
    const person = new Person();
    export { person }
    

    缺点:创建实例提前了,通用性差
    2.优化上面的方法

    class Person {
      constructor(name, age) {
        console.log('person created');
      }
      //静态是属性
      static ins = null;
      static getInstance(args) {
        if (!this.ins) {
          this.ins = new Person(...args);
        }
        return this.ins;
      }
    }
    export { Person }
    

    使用:

    import { Person } from "./Person.js";
    
    let p1 = Person.getInstance("张三", 18);
    let p2 = Person.getInstance("李四", 19);
    let p3 = new Person("李四", 19);
    
    console.log(p1 === p2);//true
    console.log(p1 === p3);//false
    

    缺点:由于js没有private关键字,无法将构造函数私有化,这也就需要使用者知道调用getInstance方法创建实例,而不是通过new的方式创建实例

    再次优化:
    singleton.js

    export function singleton(className) {
      let ins;
      return class {
        constructor(...args) {
          if (!ins) {
            ins = new className(...args);
          }
          return ins;
        }
      }
    }
    

    person.js

    import { singleton } from "./singleton.js";
    
    class Person {
      constructor(name, age) {
        console.log('person created');
      }
    }
    const newPerson = singleton(Person);
    export { newPerson as Person }
    

    使用:

    import { Person } from "./Person.js";
    let p1 = new Person("张三", 18);
    let p2 = new Person("张三", 18);
    //这里的new 相当于 new 的singleton里return的class
    
    console.log(p1 === p2);
    

    缺点:

    import { Person } from "./Person.js";
    let p1 = new Person("张三", 18);
    let p2 = new Person("张三", 18);
    
    Person.prototype.play = function () {
      console.log("加在原型上的方法--play");
    
    }
    p1.play();//报错TypeError: p1.play is not a function
    console.log(p1 === p2);
    

    上面Person指向的是 singleton中return 的class
    而p1,p2是Person的实例,所以p1,p2无法使用挂载在singleton中return 的class原型上的方法.

    使用代理来实现单例:

    export function singleton(className) {
      let ins;
    //使用代理来拦截construct
      return new Proxy(className, {
        construct(target, args) {
          if (!ins) {
            ins = new target(...args);
          }
          return ins;
        }
      })
    }
    
    代理实现单例.png

    相关文章

      网友评论

          本文标题:单例模式

          本文链接:https://www.haomeiwen.com/subject/fsniddtx.html