重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

JS实现单例模式的方式有哪些

本篇内容介绍了“JS实现单例模式的方式有哪些”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

目前创新互联公司已为上千余家的企业提供了网站建设、域名、雅安服务器托管、网站托管、服务器托管、企业网站设计、嘉黎网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

JS实现单例模式的多种方案

单例模式的概念

  • 一个实例只生产一次

  • 保证一个类仅有一个实例,并提供一个访问它的全局访问点

方式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);

“JS实现单例模式的方式有哪些”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


网站名称:JS实现单例模式的方式有哪些
标题链接:http://cqcxhl.cn/article/gpgeip.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP