louzhedong / blog

前端基础,深入以及算法数据结构

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

单例模式

louzhedong opened this issue · comments

单例模式

保证一个类仅有一个实例,并提供一个访问它的全局访问点

优点:减少内存开销

确定:扩展难,测试不利

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

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

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

// 使用
var a = Singleton.getInstance('abcd');
Java
public class Singleton {
    private static final Singleton singleton = new Singleton();

  	// private保证类产生多个实例
    private Singleton() {
    }

    public static Singleton getInstance() {
        return singleton;
    }

    public static void doSomething() {
    }
}