JavaScript设计模式

设计模式-单例模式

2018-12-31  本文已影响1人  halapro_liu

1、普通单例模式

var Singleton = function (name) {
    this.name = name
    this.instance = null
}

Singleton.getInstance = function (name) {
    if (!this.instance) {
        this.instance = new Singleton(name)
    }
    return this.instance
}

2、惰性单例模式

var lazySingleton = function (name) {
    this.name = name
}

lazySingleton.getInstance = (function (name) {
    var _instance = null
    return function (name) {
        if (!_instance) {
            _instance = new lazySingleton(name)
        }
        return _instance
    }
})()
上一篇 下一篇

猜你喜欢

热点阅读