android 单例模式

1.普通方法

4.public class SingletonB {  
5.   
6.    /** 
7.     * 单例对象实例 
8.     */  
9.    private static SingletonB instance = null;  
10.   
11.    public synchronized static SingletonB getInstance() {  
12.        if (instance == null) {  
13.            instance = new SingletonB();  
14.        }  
15.        return instance;  
16.    }  
17.}  


2.优化方法

4.public class SingletonF implements Serializable {    
5.     
6.    private static class SingletonHolder {    
7.        /**  
8.         * 单例对象实例  
9.         */    
10.        static final SingletonF INSTANCE = new SingletonF();    
11.    }    
12.     
13.    public static SingletonF getInstance() {    
14.        return SingletonHolder.INSTANCE;    
15.    }    
16.     
17.    /**  
18.     * private的构造函数用于避免外界直接使用new来实例化对象  
19.     */    
20.    private SingletonF() {    
21.    }    
22.     
23.    /**  
24.     * readResolve方法应对单例对象被序列化时候  
25.     */    
26.    private Object readResolve() {    
27.        return getInstance();    
28.    }    
29.}   

 

posted on 2013-03-05 10:07  _star  阅读(207)  评论(0)    收藏  举报

导航