JS實現單例模式的多種方案


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM