JavaScript 单例模式的六种实现方案详解

作者:纸飞机时间:2026-10-25 20:08:15浏览:489

本文总结了JavaScript中实现单例模式的六种常见方案,涵盖ES5函数与ES6 Class两种技术路线。通过instanceof判断、静态方法、闭包及包装对象等技术手段,解析如何确保类仅生成一个实例并提供全局访问点,帮助开发者根据场景选择合适实现。

本文对JavaScript中实现单例模式的多种方案进行了简要总结,共列出六种具体实现方式,内容主要划分为基于ES5函数和基于ES6类的两大类别。

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

在复习设计模式中的创建型模式时,发现JavaScript实现单例模式的方案种类繁多,经过整理后,以下列出六种方式供参考。

整体内容结构主要划分为基于ES5函数与基于ES6类的实现两部分。

单例模式的核心概念

  • 确保一个实例仅被创建一次。
  • 保证一个类只有一个实例,并提供一个全局访问点以访问该实例。

方案一

利用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

方案二

在函数上直接添加方法属性调用生成实例。

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

方案三

使用闭包,改进方案二。

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

方案四

使用包装对象结合闭包的形式实现。

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

方案五

在构造函数中利用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);

方案六

使用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);

到此这篇关于JavaScript实现单例模式的N种方案的文章就介绍到这了,更多相关JavaScript单例模式内容请搜索本站以前的文章或继续浏览下面的相关文章,希望大家以后多多支持本站!

作者最新文章