标签:private bsp let 模式 get tin col 静态 安全
1 public class Singleton1 { 2 private Singleton1() { 3 } 4 private static Singleton1 instance = new Singleton1(); 5 6 public static Singleton1 getInstance(){ 7 return instance; 8 } 9 }
1 public class Singleton2 { 2 private Singleton2() { 3 } 4 private static Singleton2 instance = null; 5 public static Singleton2 getInstance(){ 6 if (instance == null){ 7 instance = new Singleton2(); 8 } 9 return instance; 10 } 11 }
1 public class Singleton3 {
2 private Singleton3() {
3 }
4 private static Singleton3 instance = null;
5 public synchronized static Singleton3 getInstance(){
6 if (instance == null){
7 instance = new Singleton3();
8 }
9 return instance;
10 }
11 }
1 public class Singleton4 {
2 private Singleton4() {
3 }
4 private volatile static Singleton4 instance = null;
5 public static Singleton4 getInstance(){
6 if (instance == null){//1
7 synchronized (Singleton4.class) {
8 if (instance == null)//2
9 instance = new Singleton4();
10 }
11 }
12 return instance;
13 }
14 }
1 public class Singleton5 {
2 private Singleton5() {
3 }
4 private static class SingletonHolder{
5 private static Singleton5 instance = new Singleton5();
6 }
7 public static Singleton5 getInstance(){
8 return SingletonHolder.instance;
9 }
10 }
标签:private bsp let 模式 get tin col 静态 安全
原文地址:https://www.cnblogs.com/meijianxue/p/11937610.html