单例模式Singleton

     首先来明确一个问题,那就是在某些情况下,有些对象,我们只需要一个就可以了,

比如,一台计算机上可以连好几个打印机,但是这个计算机上的打印程序只能有一个,

这里就可以通过单例模式来避免两个打印作业同时输出到打印机中,

即在整个的打印过程中我只有一个打印程序的实例。

简单说来,单例模式(也叫单件模式)的作用就是保证在整个应用程序的生命周期中,

任何一个时刻,单例类的实例都只存在一个(当然也可以不存在)。

 

 

 

第一种(懒汉,线程不安全): 

Java代码  收藏代码
  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. }  

 

第二种(懒汉,线程安全):

 

Java代码  收藏代码
  1. public class Singleton {  
  2.     private static Singleton instance;  
  3.     private Singleton (){}  
  4.     public static synchronized Singleton getInstance() {  
  5.     if (instance == null) {  
  6.         instance = new Singleton();  
  7.     }  
  8.     return instance;  
  9.     }  
  10. }  

第三种(饿汉):

 

Java代码  收藏代码
  1. public class Singleton {  
  2.     private static Singleton instance = new Singleton();  
  3.     private Singleton (){}  
  4.     public static Singleton getInstance() {  
  5.     return instance;  
  6.     }  
  7. }  

 

第四种、双重检查锁定

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

 

 

第五种 静态内部类

  1. public class Singleton {    
  2.     private static class LazyHolder {    
  3.        private static final Singleton INSTANCE = new Singleton();    
  4.     }    
  5.     private Singleton (){}    
  6.     public static final Singleton getInstance() {    
  7.        return LazyHolder.INSTANCE;    
  8.     }    
  9. }    
posted on 2016-08-11 15:47  Dos尚  阅读(228)  评论(0)    收藏  举报