单例模式

单例模式

Java中的单例

饿汉

1
2
3
4
5
6
7
8
9
public class Single {
private static Signle instance = new Single();

private Single() {}

public static Single getInstance() {
return instance;
}
}

懒汉

1
2
3
4
5
6
7
8
9
10
private static Single instance= null;
private Single() {}

public static Single getInstance () {
if (instance == null) {
instance = new Single()
}

return instance
}

懒汉线程安全

1
2
3
4
5
6
7
public static synchronized Single getInstance() {
if (instance == null) {
instance = new Single()
}

return instance
}

双检验

1
2
3
4
5
6
7
8
9
10
public static Single getInstance() {
if (instance == null) {
synchronized(Single.class) {
if (instance == null) {
instance == new Single()
}
}
}
return instance
}

登记静态

1
2
3
4
5
6
7
8
9
10
11
private static class SingleHolder {
private static final Single INSTANCE = new Signle()
}

private Single() {

}

public static final Single getInstance() {
return SingleHolder.INSTANCE
}

枚举

1
2
3
4
5
6
7

public enum Single {
INSTANCE;
public void method() {

}
}

JavaScript中的单例

闭包实现单例

1
2
3
4
5
6
7
8
9
10
11
12

function A () {
this.data = "Class A"
}

A.getInstance = function () {
var instance;
return function () {
instance = instance ? instance: new A
return instance
}
}()

正常单例

1
2
3
4
5
6
7
8
9
10
11
12
13
let A = function () {
if (A.instance) {
console.log("no new")
}
this.data = "Class A"
}

A.getInstance = function () {
if (A.instance == null) {
A.instance = new A()
}
return A.instance
}
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2020 Kfdykme
  • Powered by Hexo Theme Ayer
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信