Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

单例模式 #212

Open
louzhedong opened this issue May 20, 2020 · 0 comments
Open

单例模式 #212

louzhedong opened this issue May 20, 2020 · 0 comments

Comments

@louzhedong
Copy link
Owner

单例模式

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

优点:减少内存开销

确定:扩展难,测试不利

实现
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() {
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant