码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2019-11-26 19:19:06      阅读:37      评论:0      收藏:0      [点我收藏+]

标签:private   bsp   let   模式   get   tin   col   静态   安全   

1、饿汉式(非线程安全)

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 }

 

2、懒汉式(非线程安全)

 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 }

 3、懒汉式(线程安全)

 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 }

 

4、双重检查

 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 }

 5、静态私有内部类

 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!