JavaScript设计模式——单例模式

单例模式

定义

  一个类仅有一个实例,并提供一个全局访问点。

常用场景

  线程池、全局缓存、登录浮窗

单例模式几种情形

标准单例

  用一个变量来标志是否已经为该类创建过对象,如果创建过,则返回该实例,否则创建新实例。

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

Singleton.prototype.getName = function () {
    console.log(this.name);
};

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

var single1 = Singleton.getInstance('staven');
var single2 = Singleton.getInstance('kim');

console.log(single1 === single2); //true
var Singleton = function (name) {
    this.name = name;
};

Singleton.prototype.getName = function (name) {
    console.log(this.name);
};

Singleton.getInstance = (function () {
    var instance = null;
    return function (name) {
        if (!instance) {
            instance = new Singleton(name);
        }
        return instance;
    }
})();

var single1 = Singleton.getInstance('staven');
var single2 = Singleton.getInstance('kim');

console.log(single1 === single2); //true

代理实现单例模式

var CreateDiv = function (html) {
    this.html = html;
    this.init();
};

CreateDiv.prototype.init = function () {
    var div = document.createElement('div');
    div.innerHTML = this.html;
    document.body.appendChild(div);
};

var ProxSingleton = (function () {
    var instance;
    return function (html) {
        if (!instance) {
            instance = new CreateDiv(html);
        }
        return instance;
    }
})();

var single1 = new ProxSingleton('staven');
var single2 = new ProxSingleton('kim');
console.log(single1 === single2); //true

惰性单例

  在需要的时候才创建对象实例。

var getSingle = function (fn) {
    var result;
    return function () {
      return result || (result = fn.apply(this, arguments));
    }
};

var createLoginDiv = function () {
    var div = document.createElement('div');
    div.innerHTML = '我是登录浮窗';
    div.style.display = 'none';
    document.getElementById('box').appendChild(div);
    return div;
};

var loginDiv = getSingle(createLoginDiv);
document.getElementById('loginBtn').onclick = function () {
    loginDiv().style.display = 'block';
};
document.getElementById('exitBtn').onclick = function () {
    loginDiv().style.display = 'none';
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值