首页 > 代码库 > 单例模式

单例模式

 1 public class Singleton { 2      3 private static Singleton singleton; 4     //懒汉式单例 5     private static Singleton singleton; 6     private Singleton(){ 7     } 8      9     public static synchronized Singleton getSingleton() {10         if (singleton == null) {11             singleton = new Singleton();12         }13         return singleton;14     }15 }    
1 public class Singleton {2   private static Singleton singleton = new Singleton();3     private Singleton(){4     }5     6     public static synchronized Singleton getSingleton() {7         return singleton;8     }  9 }

synchronized:线程同步(不允许多个线程同时访问该方法)

单例模式