单例模式

122 阅读1分钟

定义:

一个类只能定义一个对象的设计模式, 即保证一个类仅有一个实例,并提供一个访问它的全局访问点。

实现思想:

是用一个变量来标志当前是否已经为某个类创建过对象,如果是,则在下一次获取该类的实例时,直接返回之前创建的对象.

实现代码:

闭包方式实现

// 定义 singleFn.js
function getSingle (option){
    this.id = option.id
}
getSingle.prototype.getId = function(){
    return this.id;
}
let singleInstance = (function (){
   let instance;
   return function (option){
       if(!instance){
           instance = new getSingle(option)
       }
       return instance;
   }
})()

export default singleInstance

// 使用
let singlefn = singleInstance({id:1})  
console.log(singlefn)  //   getSingle {__ob__: Observer id: 1} 
singlefn = singleInstance({id:2})
console.log(singlefn) //   getSingle {__ob__: Observer id: 1} 

es6语法class方式实现

// 定义
class Single {
    static instance;
    constructor(options){
        this.id = options.id
    }
    static getInstanceof = function(options){
        if(!this.instance){
            this.instance = new Single(options)
        }
        return this.instance
    }
}
export default Single
// 使用
let single = Single.getInstanceof({id:1})
console.log(single) // 1.  Single {__ob__: Observer id: 1} 
single = Single.getInstanceof({id:2})
console.log(single) // 1.  Single {__ob__: Observer id: 1} 

单例销毁

由于单例具有唯一性, 一旦创建, 就无法更改, 但是我们有时候需要创建新的单例, 就需要将原先的单例销毁.

// 定义 single.js
class Single {
    constructor(options){
        this.id = options.id
    }

    static getInstanceof = (function () {
        let instance = null;
        let retFn = function(options){
            if(!instance){
                instance = new Single(options)
            }
            return instance
        }
        retFn.distroy = function(){
            console.log("执行 destroy ")
            instance = null
        }
        return retFn
    })()
}
export default Single

let single = Single.getInstanceof({id:1})
console.log(single) // 1.  Single {__ob__: Observer id: 1} 
single = Single.getInstanceof({id:2})
console.log(single) // 1.  Single {__ob__: Observer id: 1} 
singleDes.getInstanceof.distroy()
single = Single.getInstanceof({id:2})
console.log(single) // 1.  Single {__ob__: Observer id: 2} 

如有问题,欢迎探讨,如果满意,请手动点赞,谢谢!🙏

demo地址: github.com/aicai0/hist…

及时获取更多姿势,请您关注!!