设计模式之单例模式

来源:互联网 发布:mac卸载第三方软件 编辑:程序博客网 时间:2024/06/05 02:24
java设计模式之单例模式


一、单例模式的介绍
     Singleton是一种创建型模式,指某个类采用Singleton模式,则在这个类被创建后,只可能产生一个实例供外部访问,并且提供一个全局的访问点

二、单例模式的实现

实现的方式有如下四种:
Java代码 复制代码 收藏代码
  1. /**  
  2.  *   
  3.  * 单例模式的实现:饿汉式,线程安全 但效率比较低  
  4.  */  
  5. public class SingletonTest {   
  6.   
  7.     private SingletonTest() {   
  8.     }   
  9.   
  10.     private static final SingletonTest instance = new SingletonTest();   
  11.   
  12.     public static SingletonTest getInstancei() {   
  13.         return instance;   
  14.     }   
  15.   
  16. }  

Java代码 复制代码 收藏代码
  1. /**  
  2.  * 单例模式的实现:饱汉式,非线程安全   
  3.  *   
  4.  */  
  5. public class SingletonTest {   
  6.     private SingletonTest() {   
  7.     }   
  8.   
  9.     private static SingletonTest instance;   
  10.   
  11.     public static SingletonTest getInstance() {   
  12.         if (instance == null)   
  13.             instance = new SingletonTest();   
  14.         return instance;   
  15.     }   
  16. }  

Java代码 复制代码 收藏代码
  1. /**  
  2.  * 线程安全,但是效率非常低  
  3.  * @author vanceinfo  
  4.  *  
  5.  */  
  6. public class SingletonTest {   
  7.     private SingletonTest() {   
  8.     }   
  9.   
  10.     private static SingletonTest instance;   
  11.   
  12.     public static synchronized SingletonTest getInstance() {   
  13.         if (instance == null)   
  14.             instance = new SingletonTest();   
  15.         return instance;   
  16.     }   
  17. }  

Java代码 复制代码 收藏代码
  1. /**  
  2.  * 线程安全  并且效率高  
  3.  *  
  4.  */  
  5. public class SingletonTest {   
  6.     private static SingletonTest instance;   
  7.   
  8.     private SingletonTest() {   
  9.     }   
  10.   
  11.     public static SingletonTest getIstance() {   
  12.         if (instance == null) {   
  13.             synchronized (SingletonTest.class) {   
  14.                 if (instance == null) {   
  15.                     instance = new SingletonTest();   
  16.                 }   
  17.             }   
  18.         }   
  19.         return instance;   
  20.     }   
  21. }