单例模式

饿汉式:

 1 /**
 2  * 单例模式  饿汉式
 3  */
 4 public class SingletonHungry {
 5 
 6     private SingletonHungry (){
 7     }
 8     public static SingletonHungry instance = new SingletonHungry();
 9 
10     public static SingletonHungry getInstance(){
11         return instance;
12     }
13 
14 }
View Code

懒汉式:

 1 /**
 2  *  单例模式  懒汉式
 3  */
 4 public class Singleton {
 5 
 6     private static class SingletonHolder{
 7         private static Singleton instance = new Singleton();
 8     }
 9 
10     private Singleton(){
11     }
12 
13     public static Singleton getInstance(){
14         return SingletonHolder.instance;
15     }
16 }
View Code

 

posted @ 2018-10-04 19:55  剑未佩托  阅读(156)  评论(0)    收藏  举报