java设计模式--单例模式

设计模式

1. 单例模式:饱汉、饿汉。以及饿汉中的延迟加载,双重检查

单例模式

分类:懒汉式单例、饿汉式单例、登记式单例

特点:
  1、单例类只能有一个实例。
  2、单例类必须自己自己创建自己的唯一实例。
  3、单例类必须给所有其他对象提供这一实例。

单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例

应用场景:线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例

 懒汉式,线程不安全
1
public class Singleton { 2 private static Singleton instance; 3 private Singleton (){} 4 5 public static Singleton getInstance() { 6 if (instance == null) { 7 instance = new Singleton(); 8 } 9 return instance; 10 } 11 } 懒汉式,线程安全,不高效 13 public static synchronized Singleton getInstance() { 14 if (instance == null) { 15 instance = new Singleton(); 16 } 17 return instance; 18 }

双重检查锁模式

 1 public class Singleton {
 2     private volatile static Singleton instance; //声明成 volatile
 3     private Singleton (){}
 4 
 5     public static Singleton getSingleton() {
 6         if (instance == null) {                         
 7             synchronized (Singleton.class) {
 8                 if (instance == null) {       
 9                     instance = new Singleton();
10                 }
11             }
12         }
13         return instance;
14     }
15    
16 }

饿汉式

 1 public class Singleton{
 2     //类加载时就初始化
 3     private static final Singleton instance = new Singleton();
 4     
 5     private Singleton(){}
 6 
 7     public static Singleton getInstance(){
 8         return instance;
 9     }
10 }

静态内部类的写法(推荐)懒汉式

1 public class Singleton {  
2     private static class SingletonHolder {  
3         private static final Singleton INSTANCE = new Singleton();  
4     }  
5     private Singleton (){}  
6     public static final Singleton getInstance() {  
7         return SingletonHolder.INSTANCE; 
8     }  
9 }

Singleton通过将构造方法限定为private避免了类在外部被实例化

完美的解释http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/

原文地址:https://www.cnblogs.com/wangwanchao/p/5252359.html