JS完成单例模式的多种多样计划方案

JS完成单例模式的多种多样计划方案 ,文中稍稍汇总,列举了6种方法与大伙儿共享,大致将內容分成了ES5(Function)与ES6(Class)完成二种一部分

JS完成单例模式的多种多样计划方案

今日在备考策略模式中的-建立型方式,发觉JS完成单例模式的计划方案有很多种多样,稍稍汇总了一下,列举了以下的6种方法与大伙儿共享

大致将內容分成了ES5(Function)与ES6(Class)完成二种一部分

单例模式的定义

  • 一个案例只生产制造一次
  • 确保一个类仅有一个案例,并给予一个浏览它的全局性浏览点

方法1

运用instanceof分辨是不是应用new关键词函数调用开展目标的创建对象

function User() {
    if (!(this instanceof User)) {
        return
    }
    if (!User._instance) {
        this.name = '無名'
        User._instance = this
    }
    return User._instance
}

const u1 = new User()
const u2 = new User()

console.log(u1===u2);// true

方法2

在涵数上立即加上方式特性启用转化成案例

function User(){
    this.name = '無名'
}
User.getInstance = function(){
    if(!User._instance){
        User._instance = new User()
    }
    return User._instance
}

const u1 = User.getInstance()
const u2 = User.getInstance()

console.log(u1===u2);

方法3

应用闭包,改善方法2

function User() {
    this.name = '無名'
}
User.getInstance = (function () {
    var instance
    return function () {
        if (!instance) {
            instance = new User()
        }
        return instance
    }
})()

const u1 = User.getInstance()
const u2 = User.getInstance()

console.log(u1 === u2);

方法4

应用包裝目标融合闭包的方式完成

const User = (function () {
    function _user() {
        this.name = 'xm'
    }
    return function () {
        if (!_user.instance) {
            _user.instance = new _user()
        }
        return _user.instance
    }
})()

const u1 = new User()
const u2 = new User()

console.log(u1 === u2); // true

自然这儿能够将闭包一部分的编码独立封裝为一个涵数

在经常应用到单例的状况下,强烈推荐应用相近此方式的计划方案,自然內部完成能够选用以上随意一种

function SingleWrapper(cons) {
    // 清除非涵数与箭头函数
    if (!(cons instanceof Function) || !cons.prototype) {
        throw new Error('并不是合理合法的构造方法')
    }
    var instance
    return function () {
        if (!instance) {
            instance = new cons()
        }
        return instance
    }
}

function User(){
    this.name = 'xm'
}
const SingleUser = SingleWrapper(User)
const u1 = new SingleUser()
const u2 = new SingleUser()
console.log(u1 === u2);

方法5

在构造方法中运用new.target分辨是不是应用new关键词

class User{
    constructor(){
        if(new.target !== User){
            return
        }
        if(!User._instance){
            this.name = 'xm'
            User._instance = this
        }
        return User._instance
    }
}

const u1 = new User()
const u2 = new User()
console.log(u1 === u2);

方法6

应用static静态方法

class User {
    constructor() {
        this.name = 'xm'
    }
    static getInstance() {
        if (!User._instance) {
            User._instance = new User()
        }
        return User._instance
    }
}


const u1 = User.getInstance()
const u2 = User.getInstance()

console.log(u1 === u2);

评论(0条)

刀客源码 游客评论