单例模式

 从网上整理了几种单例模式的例子

  
  
  
  
  1. /** 
  2.  * 懒汉单例模式1 
  3.  * @author Administrator 
  4.  * 
  5.  */ 
  6.  
  7. public class SlugSingleton { 
  8.     private static SlugSingleton instance = null
  9.      
  10.     private SlugSingleton(){}; 
  11.      
  12.     synchronized public static SlugSingleton getInstance(){ 
  13.         if(instance == null){ 
  14.             instance = new SlugSingleton(); 
  15.             return instance; 
  16.         } 
  17.         else return instance; 
  18.     } 
  19.  
  20. /** 
  21.  * 懒汉单例模式2 
  22.  * @author Administrator 
  23.  * 
  24.  */ 
  25. public class SlugSingleton2{ 
  26.     private static SlugSingleton2 instance = null
  27.     private static Object synObject = new Object(); 
  28.      
  29.     private SlugSingleton2(){}; 
  30.      
  31.     public static SlugSingleton2 getInstance(){ 
  32.         if(instance != nullreturn instance; 
  33.          
  34.         synchronized(synObject){ 
  35.             if(instance == null){ 
  36.                 instance = new SlugSingleton2(); 
  37.             } 
  38.         } 
  39.          
  40.         return instance; 
  41.     } 
  42.  
  43. /** 
  44.  * 饿汉单例模式 
  45.  * @author Administrator 
  46.  *  
  47.  */ 
  48. public class HungrySingleton{ 
  49.     private static final HungrySingleton instance = new HungrySingleton(); 
  50.      
  51.     private HungrySingleton(){}; 
  52.      
  53.     public static HungrySingleton getInstance(){ 
  54.         return instance; 
  55.     } 
  56.  
  57. /** 
  58.  * 一种新的单例模式 
  59.  * @author Administrator 
  60.  * 
  61.  */ 
  62. public class NewSingleton { 
  63.  
  64.     public static NewSingleton getInstance() { 
  65.         return TestInstance.getInstance(); 
  66.     } 
  67.  
  68.     private NewSingleton() { 
  69.     } 
  70.  
  71.     private static class TestInstance { 
  72.         private static NewSingleton instance = new NewSingleton(); 
  73.  
  74.         private TestInstance() { 
  75.         } 
  76.  
  77.         private static NewSingleton getInstance() { 
  78.             return instance; 
  79.         } 
  80.     } 

 

你可能感兴趣的:(Singleton,单例模式)